PYTHON 3 TUTORIAL FOR EVERYONE CHAPTER 4: CONDITION | ITERATION

In this part of Python 3 series tutorial, we will discuss about writing conditional code using if,elif,else in Python. We will also discuss about how iteration works using while and for loop.

We have a video tutorial for this chapter for Bangla speaking people:

Condition:

if

When we write computer program, sometimes we want that based on certain situation certain block of code should run. This type of code is called conditional code. In Python we can write a conditional code using if statement.

num = 100
if num % 2 == 0:
print ("Even Number")
print ("Thank You")

Output

Even Number
Thank You

if block of code runs only if the condition written after if keyword evaluates to boolean true. So in the above example, num variable is assigned to 100 and 100 is divisible by 2 without any remainder. Thus the block of code runs and shows the above output.

if and else based on user input

In the following example, input() function asks user in terminal to enter a number. Then it checks first by if condition that whether the value is even or not. If the value is even it prints ‘Even Number’ and ‘Thank You’. Here we also used an else block. If the if condition doesn’t evaluates to true the else block will run. So if we enter 3 as input, we will see ‘Odd Number’, ‘Come Again’.

num = input("Please enter a number: ")
num = int(num)
if num % 2 == 0:
print ("Even Number")
print ("Thank You")
else:
print ("Odd Number")
print ("Come Again")

Output

Please enter a number: 3
Odd Number
Come Again

if..elif..else block for multiple condition

Sometimes we need to check multiple condition in situations. In this case we can use elif condition after if condition as many as we want. elif is the short form of else if. The following program asks user to input a number then it checks if the number is 50 if not then if the number is 100, if not then if the number is greater than 100. If all the if and elif condition are evaluate to false, then the default else block will run. The if..elif..else block will run in order as we write. If any of the the if…elif block meets the condition, the remaining block will not be checked.

num = input("Please enter a number: ")
num = int(num)
if num == 50:
print ("Half Century")
elif num == 100:
print ("Century")
elif num > 100:
print ("Century +")
else:
print ("Unknown number")

Output

Please enter a number: 100
Century

Logical operator and

Logical operator ‘and’ evaluates to true if both side of ‘and’ operator evaluates to true. In the following example, when num is assigned to 3, and we check if value of num is either greater than or equal to 3 and less than 5 than only print ‘3 to 5’. And we see the output ‘3 to 5’ because the value of num 3 meets the condition. But when we assigned num to 6 the next if statement evaluates to false because, 6 is greater than 3 but 6 is not less than 5. So the else block of code will run and prints ‘5 +’

num = 3
if num >= 3 and num < 5:
print ('3 to 5')
num = 6
if num >= 3 and num < 5:
print ('3 to 5')
else:
print ("5 +")

Output

3 to 5
5 +

Logical operator or

Logical operator ‘or’ works any of the condition before or after ‘or’ operator is evaluates to true or both true. In the following example, num variable is assigned to -2. The if condition check if num is greater than or equal to 3 or num equals to -2 then print ‘3 + or -2’. As the value of num is -2 so the second part of the if condition is true thus we see the output ‘3 + or -2’

num = -2
if num >= 3 or num == -2:
print ('3 + or -2')

Output

3 + or -2

String Compare

We can use ‘==’ equals to operator for comparing string data. When we compare string data we should remember the lowercase and uppercase characters are different. So ‘ABC’ is not equal ‘abc’ or ‘AbC’. We can also use string object’s lower() method to convert characters into a common format lowercase character before comparing.

name1 = "Ahsan"
name2 = "ahsan"
if name1 == name2:
print ("Same Name")
else:
print ("Name doesn't match")

if name1.lower() == name2.lower():
print ("Same Name by lower method")

Output

Name doesn't match
Same Name by lower method

Not equals to

Not equals to operator ‘!=’ is the opposite of ‘==’ equals to operator. It means if the condition is not true then run the following block of code. In the following example, as name value ‘Unknown Person’ doesn’t match with ‘Steve Jobs’ so ‘Unknown Person’ is printed.

name = "Unknown Person"
if name != "Steve Jobs":
print (name)

Output

Unknown Person

Nested condition

We can write if..elif..else condition within any if..elif..else block. This is called nested condition.

x = 5
if x < 2:
print ("less than 2")
else:
if x == 3:
print ("x is 3")
else:
if x == 5:
print ("x is 5")

Output

x is 5

Iteration

while loop

Iteration means repeat the same task for certain times. We can write iterative code by using while loop. The syntax of while loop is, after the while keyword we give condition and then after : we write the repeated tasks. As long as the condition is true, the body will run continuously unless the condition breaks the loop or we break the loop manually within inside the loop.

For example, if we want to print 1…5 by adding value to an initial variable, we can write the following code

x = 1
print (x)
x += 1
print (x)
x += 1
print (x)
x += 1
print (x)
x += 1
print (x)

Output

1
2
3
4
5

As we see every time we add a value to x variable and run the print statement, we can shorten the code by while loop like this

x = 1
while x <= 5:
print (x)
x += 1

Output

1
2
3
4
5

Infinite while loop

If the condition of while loop is True and never be False it will become an infinite loop unless the Python interpreter or operating system doesn’t halt the program.

x = 1
while True:
print (x)
x += 1

Output

1
2
.
.
1300
Infinity

In any case if we need to set while loop condition to True then we can break the loop inside using ‘break’ statement. In the following example, the while loop condition is True but as at certain point when x value becomes 11 which is greater than 10 the break statement will run and exit the while loop

x = 1
while True:
print (x)
x += 1
if x > 10:
break

Output

1
2
3
4
5
6
7
8
9
10

Omit even number within 1 to 20

If we want within the loop certain statement should skip based on some condition but the loop should continue unless the loop condition become false then we can use ‘continue’ statement. The following program will print every odd number between 1 to 20. In the loop we wrote, if x % 2 == 0 that means if the number is even then continue, which means no need to run the remaining statement just continuously run the loop if the loop condition is true.

x = 0
while x < 20:
x += 1
if x % 2 == 0:
continue
print (x)

Output

1
3
5
7
9
11
13
15
17
19

for loop

For loop works with iterable object. Iterable object means a sequence or collection of values stored in a variable.

'''
# Syntax
for element in iterable:
body
'''

Sum 1 to 10

If we want to print 1 to 10 and at the end we want to print the sum of all these numbers we can write the following program using for loop. Here range function generates a sequence of values 1 to 10 and the loop each time access one value at a time. range(start, stop) function’s first parameter is the starting value and second parameter stop is the end value which is not inclusive. That means range(1,11) actually means create a sequence from 1 to 10.

sum = 0
for num in range(1, 11):
print (num)
sum += num
print ("Sum is {sum}".format(sum=sum))

Output

1
2
3
4
5
6
7
8
9
10
Sum is 55

String characters by for loop

We can also access each character of a string by for loop because string is iterable in python.

title = "Apple Inc."
for char in title:
print (char)

Output

A
p
p
l
e

I
n
c
.

Github Code

https://github.com/mahmudahsan/thinkdiff/blob/master/python/chapter4.py

Thank you for reading the post

Originally published: thinkdiff.net

Written by

Programmer | Writer | Traveller → https://thinkdiff.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store