Loops and Conditions in Python
Conditional Statements in Python
Python provides the following conditional structures:
- if condition: Executes a block of code if the condition is true.
- if…else condition: Executes one block of code if the condition is true and another if it is false.
- if…elif…else condition: Checks multiple conditions sequentially and executes the first matching block.
Example
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Boolean Operators in Python
- and: Returns True if both conditions are true.
- or: Returns True if at least one condition is true.
- not: Inverts a boolean value.
-
And and Or
Exemple
name = "Samir"
age = 23
if name == "Samir" and age == 23:
print("Your name is Samir, and you are also 23 years old.")
if name == "Samir" or name == "Sam":
print("Your name is either Samir or Sam.")
-
“in”Operator
Exemple
name = "Samir"
if name in ["Samir", "Sam"]:
print("Your name is either Samir or Sam.")
Loops in Python
Python provides two main types of loops: for and while.
1. For Loop
The For loop is used to iterate over a sequence (such as a list, tuple, or string).
for element in sequence:
# instructions
Exemple
for i in range(4):
print("I am number:", i)
Output
I am number: 0
I am number: 1
I am number: 2
I am number: 3
! Note
- Always pay attention to indentation.
- Nested loops are possible.
- The instruction block can contain conditions.
2. While Loop
The While
loop executes instructions as long as a condition is true.
while condition:
# instructions
Exemple
compter = 0
while compter < 5:
print(compter)
compter += 1
Output
0
1
2
3
4
!Note
- Be careful with indentation at all times.
- Nested loops are possible.
- The block of instructions can contain conditions.
Understanding continue
and break
in Python
In Python, continue
and break
are control flow statements that alter the behavior of loops.
The
continue
StatementThe
continue
statement is used to skip the current iteration of a loop and move to the next one. In the example below, when the loop reaches the condition wherei
equals 3, it will skip the
The
break
StatementOn the other hand, the
break
statement is used to exit a loop prematurely. In the example below, wheni
equals 3, the loop will terminate entirely:
Exemple Continue
for i in val:
if i == 3:
continue
print("bonjour!!!!", i)
Output
bonjour!!!! 1
bonjour!!!! 2
bonjour!!!! 4
bonjour!!!! 5
Exemple Break
for i in val:
if i == 3:
break
print("bonjour!!!!", i)
Output
bonjour!!!! 1
bonjour!!!! 2
By using continue
and break
, you can effectively control the flow of your loops based on specific conditions, enhancing the functionality of your Python programs.