In this tutorial you will learn:
- Python if, elif and else Statement
- Python for Loop
- Python while Loop
- Python break and continue Statement
1 Python if, elif and else Statement:
These statements are used when we want to make some decisions in our program to run some codes for a specific condition. The if statement will first take a test expression and will run the code only if the result of the test expression is True. Lets see an example on that:
0user_age = int(input('Please enter you age: '))
1
2if user_age >= 18:
3 print("You are an adult")As you see we have created a variable called ‘user_age’ that will contain the user age after asking him about his age, then we used the if statement followed by a test expression
that check if the user_age is greater than or equal to 18.
If the test expression (user_age >= 18) is True then the code inside our if body will be executed and print ‘You are an adult’, but if the test expression is False the code inside
the if body will not be executed.
Try to run this code and enter different age and see the result.
If you run the previous code and enter an age that is less than 18 nothing will happen and the program will end, which will looks wierd for the user when he enter his age, what we want to do now is to add another message that will be printed only when the user is less than 18. To do that we can use another if statement or the else statement.
0user_age = int(input('Please enter you age: '))
1
2if user_age >= 18:
3 print("You are an adult")
4
5if user_age < 18:
6 print("You are a minor")0user_age = int(input('Please enter you age: '))
1
2if user_age >= 18:
3 print("You are an adult")
4else:
5 print("You are a minor")As you see here when you run the code in both code blocks you will get the same result if you eneter an age less than or greater than 18.
But in the first code block we will first check if the age is greater or equal to 18, if the result is False it will jump to the next if statement and check
if the user_age is less than 18, so as you see the program has performed two check test the first is (user_age >= 18) and the second is (user_age < 18).
Now lets see the second code block, we first ask the user his age then we apply a test expression and check if it’s True or False, if True the message “You are adult”
will be executed but if it’s False automaticaly the message “You are a minor” will be executed and no second check will be run.
Now lets say we want to add another condition that check if the user age is greater than or equal to 13 and print to the user a message that tells him that he is a teenager.
To do that we will add the ‘elif’ statement to our previous code.
0user_age = int(input('Please enter you age: '))
1
2if user_age >= 18:
3 print("You are an adult")
4elif user_age >= 13:
5 print("You are a teenager")
6else:
7 print("You are a minor")When your run this code and enter your age the fist condition will check if the user_age is greater or equal to 18 and run the code inside the if body if it’s True, nothing new until now,
if the first test expression is False the second statement (elif) which combine the two statement else and if (else if) will run and check if the ‘user_age’ is greater than or equal to 13 if
it’s True the message “You are a teenager” will be printed out, if False the message inside the ‘else’ body will be printed out.
So lets see clearly what is the diffence between using multiple ‘if’ statement and ‘elif and else’ statement.
0user_age = int(input('Please enter you age: '))
1
2if user_age >= 18:
3 print("You are an adult")
4if user_age >= 13:
5 print("You are a teenager")
6if user_age < 13:
7 print("You are a minor")When you run this code and enter 35 for the user_age the output will be:
>>‘You are an adult’
>>‘You are a teenager’
Ooops that’s not what we want to print as a message for the user, because he can’t be adult and teenager at the same time.
What caused this error here is the multiple if statement, as i mentioned before when you add multiple if statement the program will pass through them one by one.
So in this example after geting the user input which was (35) the first if statement will check if the value is greater or equal to 18, which is True so the code will run and print ‘you are an adult’,
then the second if statement will be executed and check if user_age is greater or equal to 13 which is True because 35 >= 13 and this cause the code inside the second if statement
to run and print out the message “You are a teenager”, then the third if statement will be executed and check if the user_age is less than 13 which is False (35 < 13), so the code inside
the third if statement body will not be executed.
On the other hand when we use ‘else, elif’ statements the code inside the body of both of them will not be executed if the statement that is before them is True.
2 Python for loop:
Imagine that we have list or a sequence that contain alot of items more than 50 or 100 item, how can you go through each item in the list? if we try to access each item using the indexing method
this will be a nightmare for us. To deal with such thing python provide the ‘for’ statement which will run through all the list element.
0#list of numbers
1list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2
3sum = 0
4
5for number in list_of_numbers:
6 sum += number
7
8print("the sum is:", sum)In this example we have created a list of numbers and a variable called ‘sum’ which we will use it to contain the sum of all the numbers in the list.
Then we use the ‘for’ statement to iterate over our sequence (list_of_numbers) followed by the variable ‘number’ which will contain the current extracted element on every iteration, after that
we use the ‘in’ statement followed by the sequence that we want to iterate over it.
You can name the variable ‘number’ any name you want, i named it ‘number’ because it describe its own content.
The for statement can be used on other sequence like (string, tuple and dictionary).
Lets see some examples:
0user_info = {'user_name':'mike', 'age':24, 'job':'Full Stack Developer'}
1
2'''
3To extract both key and value of a dictionary we have to use .items()
4on the dict var.
5'''
6for key, val in user_info.items():
7 print(key,":", val)
8
9#OUTPUT:
10'''
11>> user_name : mike
12>> age : 24
13>> job : Full Stack Developer
14'''
15
16name = 'Mike'
17for character in name:
18 print(character)
19
20#OUTPUT
21'''
22>> M
23>> i
24>> k
25>> e
26'''3 Python while loop :
While loop is used to repeat a block of code as long as the test expression is True.
0counter = 0
1
2while counter < 5:
3 print("Hello")
4 counter += 1
5
6#OUTPUT
7'''
8>> Hello
9>> Hello
10>> Hello
11>> Hello
12>> Hello
13'''4 Python break and continue Statement :
Some time when we are dealing with loops we want to stop or skip the iteration based on some condition, to do that we can use break and continue.
Lets say that we want to iterate over a string and stop the iteration when we find a specific character, to do that we will specify our test condition then we use the break statement
to stop the loop.
0var = "Hello World"
1
2for character in var:
3 if character == ' ':
4 break
5 print(character)
6
7#OUTPUT
8'''
9>> H
10>> e
11>> l
12>> l
13>> o
14'''Now lets say that we want to iterate over a sequence and we want to skip a specific item in that sequence, to do that we use the continue statement.
0var = "MikiMiki"
1
2for character in var:
3 if character == 'i':
4 continue
5 print(character)
6
7#OUTPUT
8'''
9>> M
10>> k
11>> M
12>> k
13'''