if statement: Executes a block of code if a certain condition is true.
if condition:
# code to execute if condition is true
elif (else if) statement: Checks another condition if the previous one was false.
elif another_condition:
# code to execute if another_condition is true
else statement: Executes a block of code if all preceding conditions are false.
else:
# code to execute if all above conditions are false
Logical operators include and, or, and not.
while loop: Repeats as long as a condition is true.
while condition:
# code to execute repeatedly while condition is true
for loop: Iterates over a sequence.
for element in sequence:
# code to execute for each element in sequence
Use break to exit a loop and continue to skip to the next iteration.
for element in sequence:
if some_condition:
break # exits the loop
for element in sequence:
if some_condition:
continue # skips to the next iteration
# Using if-elif-else
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
# Using while loop
count = 0
while count < 5:
print(count)
count += 1
# Using for loop with range
for i in range(5):
print(i)
# Using break
for i in range(10):
if i == 5:
break
print(i)
# Using continue
for i in range(10):
if i % 2 == 0:
continue
print(i) # prints only odd numbers