Conditional Statements (if-elif-else)
Conditional statements are fundamental for controlling the flow of your program. They allow you to execute different code blocks based on conditions.
x = 10
if x > 10:
print("x is greater than 10")
elif x < 10:
print("x is less than 10")
else:
print("x is equal to 10")
Ā
if: The if
statement evaluates a condition (in this case, x > 10
) and executes the indented block of code underneath it if the condition is True
.
elif (else if): The elif
statement is used for additional conditions to check if the initial if
condition is False
. You can have multiple elif
clauses.
else: The else
statement is executed when none of the preceding conditions is True
. It's optional, and you can have only one else
statement at the end.
Advanced Example
temperature = 25
if temperature > 30:
print("It's hot outside.")
elif 20 <= temperature <= 30:
print("It's a pleasant day.")
else:
print("It's cold outside.")
For Loop
A for
loop is used to iterate over a sequence of items. Python's for
loop is incredibly versatile, as it can iterate over various types of sequences.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Iterating over a RangeĀ
TheĀ range()
function generates a sequence of numbers that can be used with a for
loop. It's often used to iterate a specific number of times.
for i in range(5): # Range from 0 to 4
print(i)
Looping with a Step
You can specify a step value when usingĀ range()
. This allows you to iterate with a specific increment.
for i in range(0, 10, 2): # Range from 0 to 10 with a step of 2
print(i)
Advanced Example
words = ["apple", "banana", "cherry"]
for word in words:
if "a" in word:
print(f"The word '{word}' contains 'a'.")
While Loop
A while
loop is used when you want to repeat a block of code as long as a specified condition is True
. It's often used for tasks where the number of iterations is unknown in advance.
count = 0
while count < 5:
print(f"Count is {count}")
count += 1 # Increment the count
Using break
The break
statement is used to exit a loop prematurely when a certain condition is met.
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == 'q':
break
print(f"You entered: {user_input}")
Using continue
TheĀ continue
statement is used to skip the current iteration of the loop and move to the next one.
num = 0
while num < 5:
num += 1
if num == 3:
continue
print(num)
Advanced Example
balance = 1000
interest_rate = 0.05
years = 0
while balance < 2000:
balance += balance * interest_rate
years += 1
print(f"It will take {years} years to double your balance.")
These advanced examples demonstrate how control structures and loops can be used for complex decision-making and iterative processes in Python. Control structures and loops are essential for writing efficient and flexible programs.