22 Conditionals Statements (if-elif-else)
Python uses if, elif and else statements for branching operations
22.1 Only if
if condition1:
-if block
= 10
a if a > 0:
print("positive number")
Here since a is 10 and it is greater than 0, “positive number” is printed in the screen.
= 0
a if a > 0:
print("positive number")
Here 0 is not greater than 0, nothing is printed in the screen.
22.2 if-else block
if condition1:
-if
blockelse:
-else block
= 10
a if a > 0:
print("positive number")
else:
print("negative number")
Here since a is 10 and it is greater than 0, “positive number” is printed in the screen. else block does not run since if block is already run.
= -10
a if a > 0:
print("positive number")
else:
print("negative number")
Here since a is -10 and it is NOT greater than 0, “positive number” is NOT printed in the screen. else block runs and “negative number” is printed on the screen.
22.3 if-elif-else block
This block also used similar to switch statements in other languages.
if condition1:
-if
blockelif condition2:
-elif
blockelse:
-else block
= 10
a if a > 0:
print("positive number")
elif a == 0:
print("zero")
else:
print("negative number")
22.4 Short example
= int(input("Please enter an integer: "))
x if x < 0:
print('A negative number is entered')
elif x == 0:
print('Zero is entered')
else:
print('A positive number is entered')
= input("Enter years of experience of python")
str_input = int(str_input)
x #Please enter an integer: 1
if x < 0:
= 0
x print('Negative experience is not possible')
print('changed to zero')
elif x == 0:
print('Ah, you are just beginning')
print("welcome to class")
elif x == 1:
print('A Junior Programmer')
print('May be you will learn some things')
else:
print('A python expert in our class')
22.4.1 Sample Question 1
Following function, is_negative should return True for negative numbers. Fill the blanks
def is_negative(x):
.....return ___
22.4.2 Sample Question 2
Following function, greeting should return German greeting according to 24 hours. Normally, before 12, you say Guten Morgen, between 12 and 18 you use Guten Tag, after 18 but before 22 you use Guten Abend, then you use Gute Nacht.
Fill the blanks
def greeting_in_german(hour):
.....return ___
22.4.3 Sample Question 3
A complex password should satisfy following conditions
- At least 9 characters long
- At least contains 1 upper case and 1 lower case character
- At least contains 1 number
- At least contains 1 character from following special character list "!#$%&()*+,-./:;<=>?@[\]^_{|}"
please write following function.
def is_password_complex(password):
.....return ___
22.4.4 Sample Question 4
What is the output of following code:
= 100
number if number > 110:
print("block if")
elif number != 110:
print("block elif1")
elif number >= 90 or number < 120:
print("block elif2")
else:
print("block else")
22.4.5 Other tutorials
22.4.6 Video tutorials
Note: On this video, raw_input (Python 2) is used. For python 3, you need to use input().