Python Loops and Conditionals Tutorial
Loops
Loops are one of the most fundamental control structures in programming. They allow a block of code to be repeated multiple times. Python has two types of loops: for and while.
For Loop
The for loop is used to iterate over a sequence (list, tuple, dictionary, set, string) or any other iterable object.
Iterating over a list
for i in [1, 2, 3, 4, 5]:
print(i) # Prints numbers from 1 to 5
While Loop
The while loop allows the execution of a group of instructions as long as a condition is met (i.e., as long as the condition evaluates to True).
# Example of using the while loop
i = 1
while i <= 5:
print(i) # Prints numbers from 1 to 5
i += 1
Conditionals
Conditionals allow us to check conditions and make our program behave one way or another, according to the results of these conditions.
If, Elif, Else
In Python, the syntax for conditionals is through the reserved words if, elif (else if), and else.
age = 20
if age < 18:
print("You are underage.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior.")
This is a very basic rundown of loops and conditionals in Python. There is much more you can do with them, including nesting loops and conditionals, using break and continue in loops, among other things. However, I hope this gives you a solid foundation upon which you can build.