Python Control Statements
if statements closely associated with , python operators , and their associativitivty and precedence.
Before evaluating any expression, Programmer should be familiar with operators. for ex: age > 18 , > is a relational operator. age > 18 and age < 23 , 'and' is a logical operator. (a+b) == (c+d) , arithmetic operator '+' and equality operator == both used in condition.
if condition: statements(s)Example: if statement usage
# if number is non-zero ,condition is successful, so print statement gets executed. num = 1 if num: print(num)
The above if condition can be rewritten with relational Operators > and <
if num < 0 or num > 0 : print(num)
The above if condition can be rewritten with != (not equal to) operator
if num !=0 : print(num)
if True: print('Hello') #Prints 'Hello', Gurantee execution of the statement.
name='' if name == '':print('name is empty') #Following Example checks 'name' starts with Capital Letter name = 'sam' if name[0].title().istitle(): name=name[0].title()+name[1:] print(name) SamExample: if statement usage with in Operator
address= '123 james street,ma,usa,zip:63663' if 'zip' in address: print('Address has ZIP code')
if condition: statements(s) else statement(s)
condition is true , true block gets executed, condition is False else block gets executed.
Example: Check age for eligibility using simple conditionage = int(input('Enter Your Age:')) if ( age >= 18 ): print('Eligible for Voting') else: print('Not Eligible')Example: Check age for eligibility using compound condition, 'and' logical operator used to check eligibility, age should be between 21 and 35. both conditions must return True. Person should be greater than or equal to 21 and less than or equal to 35.
age = int(input('Enter Your Age:')) if ( age >= 21 and age <=35 ): print('Eligible for Managereal jobs') else: print('Not Eligible for Job')
if condition: statements(s) elif condition: statement(s) else statement(s)Example: Find Maximum of 3 numbers.using if else statement
a = 10; b = 20; c = 25 max = 'No Max'; if a > b and a > c: max = a elif b > c: max = b else: max = c print('maximum number is:',max)Example: Find High Paid Jobs using if-else-if Statement
Example: Checks Object instance using isinstance function
x=1,2,3 if isinstance(x,tuple): print('x is a tuple') elif isinstance(x,set): print('x is a set') elif isinstance(x,list): print('x is a list') x is a tuple
match condition: case expr1: case expr2: .......... case _:
match is similar to switch-case statement in 'C' Programming
match True: case True: print(True) case False: print(False)prints True Example: Find age group using match compound statement
age = 24 match age : range(0,19): print('not eligile for job') range(19,31):print('eligible for job') range(31,45):print('eligible for managerial job') range(45,60):print('Senior Manager jobs') case _: print('Not eligible')
ADS