Getting Started with Python: Statements, for
Loops, and while
Loops
If you're new to Python or coming from another programming language like C++ or Java, Python’s syntax can feel like a breath of fresh air. In this post, we'll walk through the basics of Python statements, explore for
loops, and dive into while
loops—all key building blocks for writing Pythonic code.
Introduction to Python Statements
One of the reasons Python has gained popularity is its readable and minimalistic syntax. Unlike languages that require semicolons and braces (;
, {}
), Python uses colons (:
) and indentation to define code blocks.
Example: Python vs. C-style Syntax
// C-style
if (a > b) {
a = 2;
b = 4;
}
# Python
if a > b:
a = 2
b = 4
Key Takeaways:
-
No parentheses or curly braces.
-
Indentation matters—a lot!
-
Each line is treated as a statement (no semicolons needed).
This focus on whitespace and simplicity makes Python code clean and intuitive to read.
for
Loops in Python
A for
loop in Python is used to iterate over any iterable object, such as:
-
Lists
-
Strings
-
Tuples
-
Dictionaries
Basic Syntax
for item in iterable:
# Do something with item
Example 1: Loop through a list
list1 = [1, 2, 3, 4, 5]
for num in list1:
print(num)
Using Modulo to Find Even Numbers
for num in list1:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
Summing Elements in a List
list_sum = 0
for num in list1:
list_sum += num
print("Total Sum:", list_sum)
Looping through a String
for letter in "Python":
print(letter)
Looping through Tuples and Tuple Unpacking
pairs = [(1, 2), (3, 4), (5, 6)]
for a, b in pairs:
print(f"{a} + {b} = {a + b}")
Dictionaries: .items()
, .keys()
, .values()
d = {'a': 1, 'b': 2}
for key, value in d.items():
print(f"Key: {key}, Value: {value}")
while
Loops in Python
While loops are used when you want to repeat a block of code as long as a condition remains true.
Basic Syntax
while condition:
# Code block
else:
# Final block (optional)
Example: Counting to 10
x = 0
while x < 10:
print(f"x is: {x}")
x += 1
Special Keywords
-
break
: Exits the loop immediately. -
continue
: Skips to the next loop iteration. -
pass
: Does nothing (acts as a placeholder).
x = 0
while x < 5:
x += 1
if x == 3:
print("Skipping 3")
continue
print(x)
Infinite Loop Warning
# Avoid this unless you're using a break condition!
while True:
print("Infinite loop alert!")