On this page
Python Comments
Conditional Statements (if, elif, else)
Conditional statements allow your code to execute different actions based on certain conditions.
if: Checks a condition and executes a block of code if it evaluates toTrue.
if condition:
# code to execute
elif: Short for “else if,” checks another condition if the previousifcondition wasFalse.
elif another_condition:
# code to execute
else: Executes a block of code if none of the preceding conditions wereTrue.
else:
# code to execute
Example:
age = 20
if age < 13:
print("Child")
elif 13 <= age < 20:
print("Teenager")
else:
print("Adult")
Loops (for, while)
Loops allow you to execute a block of code repeatedly.
forLoop: Iterates over a sequence (e.g., a list, tuple, string).
for item in sequence:
# code to execute
Example:
for i in range(5):
print(i)
- while Loop: Repeats as long as a condition is True.
while condition:
# code to execute
Example:
count = 0
while count < 5:
print(count)
count += 1
Comprehensions (list, dictionary, and set comprehensions)
Comprehensions provide a concise way to create lists, dictionaries, and sets.
- List Comprehensions: Create a new list by applying an expression to each item in an existing iterable.
[expression for item in iterable]
Example:
squares = [x**2 for x in range(10)]
- Dictionary Comprehensions: Create a new dictionary by applying an expression to each item in an existing iterable.
{key_expression: value_expression for item in iterable}
Example:
square_dict = {x: x**2 for x in range(10)}
- Set Comprehensions: Create a new set by applying an expression to each item in an existing iterable.
{expression for item in iterable}
Example:
square_set = {x**2 for x in range(10)}
Let me know if you need further explanations or examples on any of these topics!
break, continue, and else on Loops
for item in items:
if item is None:
continue
if item == 'STOP':
break
process(item)
else:
print('Loop completed without break')
The else clause on a loop runs only if the loop was not broken out of.
enumerate and zip
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
names = ['Alice', 'Bob']
scores = [95, 87]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Ternary Expression
status = "pass" if score >= 60 else "fail"
max_val = a if a > b else b
Guard Clauses
Reduce nesting with early returns:
def process_user(user):
if user is None:
return None
if not user.is_active:
return None
return user.generate_report()
Practice Exercise
Write a FizzBuzz program: print numbers 1–100, but replace multiples of 3 with “Fizz”, multiples of 5 with “Buzz”, and multiples of both with “FizzBuzz”. Implement with both a for loop and a list comprehension.