Python Condition
Python Condition
Applications of Logical Expression (Condition) are in if-else statement (all types of if-else statements)
and in while loops. Till now processing meant using only arithmetic expression. Now we will learn how
to if-else statement in processing.
if-else
if-else statement provides a way to change program flow based on a condition or a decision making
process is introduced in a Python script. if and else are both keywords.
Syntax for if-else:
if condition:
statement11
statement12
:
else:
statement21
statement22
:
OR,
if condition1:
statement11
statement12
:
if condition2:
statement21
statement22
:
• After the if condition, there is a : (colon) and after else there is another : (colon)
• If the condition is TRUE then the statements after if, statement11, statement12, … are
executed else part and the statements after else part are completely ignored
• If the condition is FALSE then the statements after the if part is completely ignored, program flow
jumps to else part, statement21, statement22, … are executed
• Without else, the statement immediately after if the statement is executed
• An else will always need a matching if
• After if part or else part, there must be at least one Python statement
• A block in Python consists of Python statements which are equally indented from the left
• Python editor automatically starts indentation after if, else, elif and after loop
• To back unindent, you need to press <BACKSPACE> key once and to indent manually, you need
to press <TAB> key
• To indent a block, select the block and press CTRL+], to unindent a block, select the block and
press CTRL+[
FAIPS, DPS Kuwait Page 3 / 20 ©Bikram Ally
Python Notes Class XI Condition
Write a Python script to input name, marks (out of 100) of a student. Display name, marks and ‘PASS’ if
marks obtained greater than equal to 33. Otherwise display name, marks and ‘FAIL’ if marks obtained is
less than 33.
name=input('Name? ')
marks=float(input('Marks[0-100]? '))
if marks>=33:
print(name,marks,'PASS') The condition is marks>=33.
else: Script is run first time, inputted marks is 82.5,
print(name,marks,'FAIL') condition is True, statement after the if part is
executed, else and the statement after the else part is
Running of the script for first time completely ignored.
Name? Alok Script is run second time, inputted marks is 28.5,
Marks? 82.5 condition is False, statement after the if part is
Alok 82.5 PASS ignored, program flow jumps to else and the statement
Running of the script for second time after the else is executed.
Name? Carol Script is run third time, inputted marks is 33,
Marks? 28.5 condition is True, statement after the if part is
Carol 28.5 FAIL executed, else and the statement after the else part is
completely ignored.
Running of the script for third time Script is run fourth time, inputted marks is 100,
Name? Tarun condition is True, statement after the if part is
Marks? 33 executed, else and the statement after the else part is
Tarun 33.0 PASS completely ignored.
Script is run fifth time, inputted marks is 0, condition
Running of the script for fourth time is False, statement after the if part is ignored, program
Name? Reshmi flow jumps to else and the statement after the else is
Marks? 100 executed.
Reshmi 100.0 PASS
Script is run sixth time, inputted marks is 200,
Running of the script for fifth time condition is True, statement after the if part is
Name? Shaym executed, else and the statement after the else part is
Marks? 0 completely ignored.
Shyam 0.0 FAIL Script is run seventh time, inputted marks is -10,
condition is False, statement after the if part is
Running of the script for sixth time ignored, program flow jumps to else and the statement
Name? Vimal after the else part is executed.
Marks? 200 The prompt says input marks between 0 and 100
Vimal 200 PASS but still you can input marks either greater than
100 or less than 0.
Running of the script for seventh time
So, there is a logical error in the script and later we
Name? Komal
will learn how to tackle such abnormal inputs.
Marks? -10
Komal -10.0 FAIL
Same script is rewritten by introducing block after if and block after else.
name=input('Name? ') There are 3 statements after if part and all are equally
marks=float(input('Marks? ')) indented from the left. These 3 statements form a
if marks>=33: block. When if condition is True, all the 3 statements
print('Name =',name) after the if part will be executed.
print('Marks =',marks) There are 3 statements after else part and all are
print('PASS') equally indented from the left. These 3 statements
else: form a block. When if condition is False, all the 3
print('Name =',name) statements after the else part will be executed.
print('Marks =',marks)
print('FAIL')
FAIPS, DPS Kuwait Page 4 / 20 ©Bikram Ally
Python Notes Class XI Condition
Indentation from the left may vary for if part and for else part. But all the statements are to be equally
indented within the same block. Examples are given below showing different indentation for the block
after the if part and the block after the else part This type indentation is acceptable by Python.
name=input('Name? ') name=input('Name? ')
marks=float(input('Marks? ')) marks=float(input('Marks? '))
if marks>=33: if marks>=33:
print('Name =',name) print('Name =',name)
print('Marks =',marks) print('Marks =',marks)
print('PASS') print('PASS')
else: else:
print('Name =',name) print('Name =',name)
print('Marks =',marks) print('Marks =',marks)
print('FAIL') print('FAIL')
Statements in the block after the if part are more Statements in the block after the else part are more
indented. indented.
But within the block, different indentation from the left is not correct. Examples are given below.
name=input('Name? ') name=input('Name? ')
marks=float(input('Marks? ')) marks=float(input('Marks? '))
if marks>=33: if marks>=33:
print('Name =',name) print('Name =',name)
print('Marks =',marks) print('Marks =',marks)
print('PASS') print('PASS')
else: else:
print('Name =',name) print('Name =',name)
print('Marks =',marks) print('Marks ='marks)
print('FAIL') print('FAIL')
Highlighted lines will flag syntax error.
2. Write a Python script to input two numbers (either both int or both float). If the first inputted number
is greater than second inputted number, then display first number, ‘greater than’, second number. If
the first inputted number is less than second inputted number, then display first number, ‘less than’,
second number. If the first inputted number is equal to second inputted number, then display first
number, ‘equal to’, second number.
a=float(input('1st number? ')) #a=int(input('1st integer? '))
b=float(input('2nd number? ')) #b=int(input('2nd integer? '))
if a>b:
print(a, 'greater than', b)
if a<b:
print(a, 'less than', b)
if a==b:
print(a, 'equal to', b)
3. Write a Python script to input 4 numbers (either all 4 are int or all 4 are float). Find the largest number
from the inputted value and display the largest number on the screen. Do not use built-in function
max().
a=float(input('1st number? ')) #a=int(input('1st integer? '))
b=float(input('2nd number? ')) #b=int(input('2nd integer? '))
c=float(input('3rd number? ')) #c=int(input('3rd integer? '))
d=float(input('4th number? ')) #d=int(input('4th integer? '))
hi=a;
if b>hi:
hi=b
if c>hi:
hi=c
if d>hi:
hi=d
print('Largest Value=', hi)
4. Write a Python script to input 3 coefficients of a quadratic equation (ax2+bx+c=0) and calculate the
discriminant. If discriminant is zero, then display the message ‘Real and Equal Roots’ and the two
roots. If discriminant is positive, then display the message ‘Real and Distinct Roots’ and the two roots.
If discriminant is negative, then display the message ‘Complex Roots’ and the two roots.
a=float(input('Coefficient of x^2? '))
b=float(input('Coefficient of x ? '))
c=float(input('Constant Term ? '))
d=b*b-4*a*c #b**2-4*a*c
if d==0:
x=-b/(2*a)
print('Real and Equal Roots')
print(x, x)
FAIPS, DPS Kuwait Page 6 / 20 ©Bikram Ally
Python Notes Class XI Condition
if d>0:
x1, x2=(-b+d**0.5)/(2*a), (-b-d**0.5)/(2*a)
print('Real and Distinct Roots')
print(x1, x2)
if d<0:
x1, x2=(-b+d**0.5)/(2*a), (-b-d**0.5)/(2*a)
print('Complex Roots')
print(x1, x2)
Logical operators
Now we will discuss few more operators which are used with logical expression (condition). These
operators are called logical operators. Logical operators are used along with relational operators.
not operator
not operator negates a condition. not is a keyword and a unary operator. not operator is used before
a logical expression. Examples are given below:
>>> a, b=10,20
>>> x, y='MAIN', 'MAN'
>>> a==b, a!=b
Displays (False, True)
>>> not a==b, not a!=b
Displays (True, False)
>>> x==y, x!=y
Displays (False, True)
>>> not x==y, not x!=y
Displays (True, False)
Truth Table for not operator:
Condition not
False True
True False
and operator
and operator is used to combine at least two logical expressions (conditions). and is a keyword and a
binary operator. and operator is explained with a help of a Python script.
Write a Python script to input three angles of a triangle. Check whether the inputted angles form an
equilateral triangle or not (assume inputted angles are positive and their sum adds up to 180).
a=float(input('1st angle? ')) First condition is a==60.
b=float(input('2nd angle? ')) Second condition is b==60.
c=float(input('3rd angle? ')) Third condition is c==60.
if a==60 and b==60 and c==60: In the first run of the script, inputted
print('Equilateral Triangle') values for the three angles are 60. First
else: condition is True, second condition is
print('Not Equilateral Triangle') True and third condition is True and
Running the script therefore complete if condition is True
1st angle? 60 and hence Equilateral Triangle is
2nd angle? 60 displayed.
3rd angle? 60 In the second run of the script,
Equilateral Triangle inputted values for the three angles are
different. First condition is False,
Running the script second condition is False and third
1st angle? 80 condition is False and therefore
2nd angle? 30 complete if condition is False and hence
3rd angle? 70 Not Equilateral Triangle is displayed.
Not Equilateral Triangle
FAIPS, DPS Kuwait Page 7 / 20 ©Bikram Ally
Python Notes Class XI Condition
Running the script In the third run of the script, inputted values for the
1st angle? 50
three angles are different. First condition is False,
2nd angle? 60
second condition is True and third condition is False
3rd angle? 70
and therefore complete if condition is False.
Not Equilateral Triangle
An if condition with and operator(s) will be True when all the conditions are True. If one condition
is False then the if condition is False.
Truth Tables for and operator:
Condition1 Condition2 and
False False False
False True False
True False False
True True True
Nested-if
In a nested-if statement, an if statement contains another if statement. An example is given below:
name=input('Name? ')
marks=float(input('Marks [0-100]? ')) Outer if-else: contains inner if-else
if marks>=0 and marks<=100:
if (marks>=33): Inner if-else, after outer if part
print(name, marks, 'PASS')
else: Nested if-else. Inner if-else is after
print(name, marks, 'FAIL') the outer if part.
else:
print('Error: marks out of range')
Outer if contains inner if-else. If outer if condition is True, then inner if-else will be executed. If inner
if condition is True, then name, marks and 'PASS' will be displayed. If inner if condition is False,
then name, marks and 'FAIL' will be displayed. If outer if condition is False, then 'Error: marks
out of range' will be displayed. Instead of writing inner if-else immediately after outer if, we can
have inner if-else immediately after outer else. An example is given below:
name=input('Name? ')
marks=float(input('Marks [0-100]? ')) Outer if-else: contains inner if-else
if marks<0 or marks>100:
print('Error: marks out of range') Inner if-else, after outer else part
else:
if (marks>=33): Nested if-else. Inner if-else is after
print(name, marks, 'PASS')
the outer else part.
else:
print(name, marks, 'FAIL')
if-else-if
The concept of if-else-if statement is the extension of the concept of nested if statement. We will write a
small script to explain the concept. First we will write the script using three if statements.
Write a Python script to input a value. If the inputted value is greater than zero, then display 'Positive'. If
the inputted value is less than zero, then display 'Negative'. If inputted value is equal to zero, then display
'Zero'.
num=float(input('Enter a value? '))
if num>0:
print('Positive')
if num<0:
print('Negative')
if num==0:
print('Zero')
If a value is entered, then one of the if statements will be True and other two if statements will be False.
Now we will rewrite the script by replacing three if statements with if-else-if statement.
num=float(input('Enter a value? '))
if num>0:
print('Positive')
else:
if num<0:
print('Negative')
else:
print('Zero')
• If the inputted number is 20.5, then first if condition is True, 'Positive' will be displayed and if-
else after the first else will be ignored.
• If the inputted number is -10.7, then first if condition is False, the program flow jumps to first else
part. Second if condition is tested. Second if condition is True, then 'Negative' will be displayed
and last else will be ignored.
• In the inputted number is 0.0, then first if condition is False, second if condition is False so the
program flow jumps to last else part and 'Zero' will be displayed.
if-elif
if-elif works exactly the same way as if-else-if but indentation of if-elif is different from if-else-if. if-else
statement after previous else has to be indented and code gets indented to the right. No such problem with
if-elif. Every if-elif is aligned equally from the left margin. The previous script is rewritten replacing if-
else-if with if-elif.
num=float(input('Enter a value? '))
if num>0:
print('Positive')
elif num<0:
print('Negative')
else:
print('Zero')
• If the inputted number is 20.5, then first if condition is True, 'Positive' will be displayed and
elif after the first if will be ignored.
FAIPS, DPS Kuwait Page 10 / 20 ©Bikram Ally
Python Notes Class XI Condition
• If the inputted number is -10.7, then first if condition is False, the program flow jumps to elif. elif
condition is tested. elif condition is True, then 'Negative' will be displayed and else will be
ignored.
• In the inputted number is 0.0, then if condition is False, elif condition is False so program flow jumps
to else part and 'Zero' will be displayed.
Write a Python script to input two floating point values and input an operator (+, -, *, /, **) to simulate a
simple calculator, that is, if inputted operator is + then find sum of the two inputted values, if inputted
operator is * then find product of the two inputted values … and display the result on the screen. If an
invalid operator is inputted then display an error message.
a=float(input('1st value? '))
b=float(input('2nd value? '))
op=input('Operator [+,-,*,/,**]? ')
if op=='+': print(a,op,b,'=',a+b)
elif op=='-': print(a,op,b,'=',a-b)
elif op=='*': print(a,op,b,'=',a*b)
elif op=='/':
if b==0:
print('Error: Division by Zero!')
else: print(a,op,b,'=',a/b)
elif op=='**': print(a,op,b,'=',a**b)
else: print(op,'Invalid Operator!')
>>> math.sqrt(25)
5.0
>>> math.sqrt(7)
2.6457513110645907
>>> math.sqrt(-9)
Displays error message.
>>> math.pow(5,2)
25.0
>>> math.pow(169,0.5)
13.0
>>> math.pow(4,3)
64.0
>>> math.pow(256,0.25)
4.0
>>> math.pow(-4,0.5)
Displays error message.
>>> math.log10(-10)
Displays error message.
1. Write a Python script to input day of a month as an integer, month as an integer and year as an integer.
Check weather inputted date is valid date or not.
dd=int(input('Day[0-31] ? '))
mm=int(input('Month[1-12]? '))
yy=int(input('Year ? '))
maxdays=0
if mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12:
maxdays=31
elif mm==4 or mm==6 or mm==9 or mm==11:
maxdays=30
elif mm==2:
if yy%4==0 and yy%100!=0 or yy%400==0:
maxdays=29
else:
maxdays=28
if dd>=1 and dd<=maxdays:
print('Valid Date')
else:
print('Invalid Date')
2. Write a Python script to input three angles of a triangles. If the inputted three angles are valid, then
identify the type of triangle. If the inputted angles are invalid then display an error message 'Error:
invalid input'.
a=float(input('1st angle? '))
b=float(input('2nd angle? '))
c=float(input('3rd angle? '))
if a>0 and b>0 and c>0 and a+b+c==180:
if a==b and b==c:
print('Equilateral Triangle')
else:
if a==90 or b==90 or c==90:
print('Right-angled ',end='')
if a==b or b==c or c==a:
print('Isosceles ',end='')
if a!=b and b!=c and c!=a:
print('Scalene ',end='')
print('Triangle')
else:
print('Error: Invalid Input')
3. Write a Python script to input a single character string and check the type of string (uppercase or
lowercase or digit or special character).
#using string methods
ch=input('Input Single Character? ')
if len(ch)==1:
if ch.isupper(): print(ch, 'Uppercase')
FAIPS, DPS Kuwait Page 15 / 20 ©Bikram Ally
Python Notes Class XI Condition
elif ch.islower(): print(ch, 'Lowercase')
elif ch.isdigit(): print(ch, 'Digit')
else: print('Special character')
else: print('String length not 1')
OR,
#without using string methods
ch=input('Input Single Character? ')
if len(ch)==1:
if ch>='A' and ch<='Z': print(ch, 'Uppercase')
elif ch>='a' and ch<='z': print(ch, 'Lowercase')
elif ch>='0' and ch<='9': print(ch, 'Digit')
else: print('Special character')
else:
print('Error: string has at least 2 characters')
OR,
#without using string methods
ch=input('Input Single Character? ')
if len(ch)==1:
if 'A'<=ch<='Z': print(ch, 'Uppercase')
elif 'a'<=ch<='z': print(ch, 'Lowercase')
elif ='0'<=ch<='9': print(ch, 'Digit')
else: print('Special character')
else:
print('Error: string has at least 2 characters')
4. Write a Python script to input a single character string and toggle the case of the string if the string is
an alphabet.
ch=input('Input Single Character? ')
if len(ch)==1:
if ch>='A' and ch<='Z': ch=chr(ord(ch)+32)
elif ch>='a' and ch<='z': ch=chr(ord(ch)-32)
print(ch)
else:
print('String length not 1')
OR,
ch=input('Input Single Character? ')
if len(ch)==1:
if 'A'<=ch<='Z': ch=chr(ord(ch)+32)
elif 'a'<=ch<='z': ch=chr(ord(ch)-32)
print(ch)
else:
print('String length not 1')
What Python’s interpretation of 0 (zero), non-zero, empty string and non-empty sting in a logical
expression (condition)?
>>> print(bool(20==20), bool(2.5==2.5), bool('FAIPS'=='FAIPS'))
Displays True True True because if a logical expression (condition) is true, then bool() returns
True.
>>> print(bool(10==20), bool(3.5==2.5), bool('FAPS'=='FAIPS'))
Displays False False False because if a logical expression (condition) is false, then bool()
returns False.
>>> print(bool(8), bool(-9), bool(4.3), bool(-2.5), bool('DPS'))
Displays True True True True True because any non-zero value or non-empty string is treated
as True by Python.
FAIPS, DPS Kuwait Page 16 / 20 ©Bikram Ally
Python Notes Class XI Condition
>>> print(bool(0), bool(0.0), bool(''))
Displays False False False because any (0) zero value or empty string ('') is treated as False by
Python.
Note: when using and operator, all the conditions are to be True, means entire if condition is True.
Python checks the first condition from the left and if it is True, then Python checks the second condition
from the left and if it is True, then Python checks third condition and if it is True …The checking stops
at the last condition from left (that is, first condition from the right). Therefore, and operator returns the
FAIPS, DPS Kuwait Page 18 / 20 ©Bikram Ally
Python Notes Class XI Condition
first non-zero value (or non-empty strings) from the right when the expression contains only non-zero
values (or non-empty strings).
Parameter end effects the output of the next print() function. Unlike parameter sep, parameter
end can have different character(s) for different print() function. Few examples are given below:
>>> print('FAIPS', end='-'); print('DPS', end=','); print('Kuwait')
Displays FAIPS-DPS,KUWAIT
>>> print('FAIPS', end=','); print('DPS', end='-'); print('Kuwait')
Displays FAIPS,DPS-KUWAIT