0% found this document useful (0 votes)
12 views20 pages

Python Condition

The document discusses logical expressions and conditionals in Python. It defines relational operators like >, <, ==, etc and shows examples of comparing integers, floats, and strings. It also covers assigning conditions to variables and boolean data types.

Uploaded by

Mohammed Fahad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views20 pages

Python Condition

The document discusses logical expressions and conditionals in Python. It defines relational operators like >, <, ==, etc and shows examples of comparing integers, floats, and strings. It also covers assigning conditions to variables and boolean data types.

Uploaded by

Mohammed Fahad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Python Notes Class XI Condition

Condition or Logical Expression


In Python a condition or a logical expression compares two values using relational operators. Relational
operators supported by Python are:
Relational Operator Meaning
> greater than
>= either greater than or equal to
< less than
<= either less than or equal to
== equal to (= is used for assigning value to a variable)
!= not equal to
Two integer (int) values can be compared, two floating point (float) values can be compared and two
strings (str) values can be compared. Two strings are compared, character by character using the
ASCII code / Unicode of the two characters. An integer value and a floating-point value can be
compared. But an integer or a floating-point value cannot be compared with a string value. The two
operands in a logical expression can either be a constant or a variable or an expression or a call to Python
function. Two constant values can be compared to explain the use of relational operators. But in a Python
script, at least one of the operands has to be either a variable or an expression or a function call. Every
time a logical expression is evaluated (or condition is tested), the result is either True or False. As
discussed earlier, True and False are keywords.

Operator Example Explanation


>>> 20>10 Two integer values are compared, condition is true (logical
True expression is true) and output is True
>>> 20>20 Two integers are compared, condition is false (logical expression
False is false) and output is False
>>> 7.5>4.8 Two floating point values are compared, condition is true (logical
>
True expression is true) and output is True
>>> 2.5>8.5 Two floating point values are compared, condition is false (logical
False expression is false) and output is False
>>> 10>5.4 An integer value and a floating-point value are compared,
True condition is true (logical expression is true) and output is True
>>> 20>=10 Two integer values are compared, condition is true (20>10 is true)
True and output is True
>>> 20>=20 Two integer values are compared, condition is true (two values
True are equal) and output is True
>>> 10>=20 Two integer values are compared, condition is true (10>20 is
False false) and output is False
>>> 8.3>=7.2 Two floating points values are compared, condition is true
>=
True (8.3>7.2 is true) and output is True
>>> 5.5>=5.5 Two floating points values are compared, condition is true (two
True values are equal) and output is True
>>> 3.5>=5.5 Two floating points values are compared, condition is true
False (3.5>5.5 is false) and output is False
>>> 5.5>=4 An integer value and a floating-point value are compared,
True condition is true (5.5>4 is true) and output is True
>>> 10<20 Two integer values are compared, condition is true (logical
True expression is true) and output is True
>>> 20<20 Two integers are compared, condition is false (logical expression
<
False is false) and output is False
>>> 3.5<8.5 Two floating point values are compared, condition is true (logical
True expression is true) and output is True
FAIPS, DPS Kuwait Page 1 / 20 ©Bikram Ally
Python Notes Class XI Condition
>>> 6.1<3.2 Two floating point values are compared, condition is false (logical
False expression is false) and output is False
>>> 10<5.5 An integer value and a floating-point value are compared,
False condition is false (logical expression is false) and output is False
>>> 10<=20 Two integer values are compared, condition is true (10<20 is true)
True and output is True
>>> 20<=20 Two integer values are compared, condition is true (two values
True are equal) and output is True
>>> 20<=10 Two integer values are compared, condition is true (20<10 is
False false) and output is False
>>> 7.3<=9.2 Two floating points values are compared, condition is true
<=
True (7.3<9.2 is true) and output is True
>>> 5.5<=5.5 Two floating points values are compared, condition is true (two
True values are equal) and output is True
>>> 7.5<=5.5 Two floating points values are compared, condition is false
False (7.5<5.5 is false) and output is False
>>> 5.5<=4 An integer value and a floating-point value are compared,
False condition is false (5.5<4 is false) and output is False
>>> 10==10 Two integer values are compared, condition is true (logical
True expression is true) and output is True
>>> 10==20 Two integers are compared, condition is false (logical expression
False is false) and output is False
>>> 4.8==4.8 Two floating point values are compared, condition is true (logical
==
True expression is true) and output is True
>>> 4.8==5.3 Two floating point values are compared, condition is false (logical
False expression is false) and output is False
>>> 10==10.0 An integer value and a floating-point value are compared,
True condition is true (logical expression is true) and output is True
>>> 10!=20 Two integer values are compared, condition is true (logical
True expression is true) and output is True
>>> 20!=20 Two integers are compared, condition is false (logical expression
False is false) and output is False
>>> 4.8!=5.8 Two floating point values are compared, condition is true (logical
!=
True expression is true) and output is True
>>> 5.3!=5.3 Two floating point values are compared, condition is false (logical
False expression is false) and output is False
>>> 10!=7.8 An integer value and a floating-point value are compared,
True condition is true (logical expression is true) and output is True

Comparing two strings (str)


Expression Result Explanation
>>> 'S'>'D' True ASCII code of 'S' is greater than ASCII code of 'D'
>>> 'a'>'x' False ASCII code of 'a' is less than ASCII code of 'x'
>>> 'b'>'Y' True ASCII code of 'b' is less than ASCII code of 'Y'
>>> '5'>'2' True ASCII code of uppercase is less than ASCII code of lowercase
'M' of 1st string matches with 'M' of 2nd string, 'A' of 1st string
>>> 'MAN'>'MAIN' True matches with 'A' of 2nd string, ASCII code of 'N' of 1st string is
greater than ASCII code of 'I' of 2nd string
>>> 'MENU'>'MAN' True 'M' of 1st string matches with 'M' of 2nd string, ASCII code of 'E'
of 1st is greater than ASCII code of 'A' of 2nd string
>>> 'P'>'CAN' True ASCII code of 'P' of 1st string is greater than ASCII code of 'C' of
2nd string
FAIPS, DPS Kuwait Page 2 / 20 ©Bikram Ally
Python Notes Class XI Condition
>>> 'pan'>'PAN' True ASCII code of 'p' of 1st string is greater than ASCII code of 'P' of
2nd string
>>> '7'>'300' True ASCII code of '7' of 1st string is greater than ASCII code of '3' of
2nd string
>>> 'PEN'=='PEN' True Two strings are equal because character by character, every
character of 1st string matches with every character of 2nd string
A logical expression (condition) can be assigned to a variable. An example is given below:
>>> ok=20>10
>>> ok A variable that stores a value of a logical expression
True (condition) is identified as a bool type data. Data type
>>> type (ok) bool is short form for Boolean. A logical expression
<class 'bool'> is also called a Boolean expression.

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.

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')
if marks>=33: No syntax error. Only first statement after else is
print('Name =',name) indented. Last 2 statements are not indented and
Syntax error: That’s if statement according to hence not the part of the else block and last 2
Python. Since 2 statements after if, are not statements will be executed every time the script is
indented and hence not part of the if block. So, an run. If inputted marks is greater than equal to 33,
else has no matching if. then there will be a logical error.

Same script is written using two if instead of if-else.


First if condition is True, then print()will
name=input('Name? ') display name, marks and PASS. Second
marks=float(input('Marks[0-100]? ')) if condition will be False.
if marks>=33: #First if First if condition is False, then the second
print(name, marks, 'PASS') if condition will be True. print() will
if marks<33: #Second if display name, marks and FAIL. The two
print(name, marks, 'FAIL') if conditions must not overlap.
FAIPS, DPS Kuwait Page 5 / 20 ©Bikram Ally
Python Notes Class XI Condition
1. Write a Python script to input a number (either int or float). If the inputted number is greater than 0,
then display the number and message ‘Positive’. If the inputted number is less than 0, then display the
number and message ‘Negative’. If the inputted number is 0, then display the number and message
‘Zero’.
n=float(input('Number? ')) #n=int(input('Integer? '))
if n>0:
print(n, 'Positive')
if n<0:
print(n, 'Negative')
if n==0:
print(n, 'Zero')

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

Condition1 Condition2 Condition3 and


False False False False
False False True False
False True False False
False True True False
True False False False
True False True False
True True False False
True True True True
or operator
or operator is used to combine at least two logical expressions (conditions). or is a keyword and a
binary operator. or operator is explained with a help with a Python script.
Write a Python script to input three angles of a triangle. Check whether the inputted angles form a
right-angled triangle or not (assume inputted angles are positive and their sum adds up to 180).
a=float(input('1st angle? ')) Three conditions are a==90, b==90.
b=float(input('2nd angle? ')) and c==90. In the first run of the
c=float(input('3rd angle? ')) script, inputted values for the three
if a==90 or b==90 or c==90:
angles are 90, 60, 30. First condition is
print('Right-angle Triangle')
True, second condition is False and
else:
third condition is False and therefore
print('Not Right-angle Triangle')
complete if condition is True and hence
Running the script Right-angle Triangle is displayed. In
1st angle? 90 the second run of the script, inputted
2nd angle? 60 values for the three angles are 40, 90,
3rd angle? 30 50. First condition is False, second
Right-angle Triangle condition is True and third condition is
False and therefore complete if
Running the script
condition is True and hence Right-
1st angle? 40
2nd angle? 90 angle Triangle is displayed. In the
3rd angle? 50 third run of the script, inputted values
Right-angle Triangle for the three angles are 20, 70, 90. First
condition is False, second condition is
Running the script False and third condition is True and
1st angle? 20 therefore complete if condition is True
2nd angle? 70 and hence Right-angle Triangle is
3rd angle? 90 displayed.
Right-angle Triangle
FAIPS, DPS Kuwait Page 8 / 20 ©Bikram Ally
Python Notes Class XI Condition
Running the script In the fourth run of the script, inputted values for the
1st angle? 50
three angles are 50, 60, 70. First condition is False,
2nd angle? 60
second condition is False and third condition is False
3rd angle? 70
and therefore complete if condition is False.
Not Right-angle Triangle
An if statement with or operator(s) will be True when at least one condition is True. If all conditions
are False then the if condition is False.
Truth Table for or operator
Condition1 Condition2 or
False False False
False True True
True False True
True True True

Condition1 Condition2 Condition3 or


False False False False
False False True True
False True False True
False True True True
True False False True
True False True True
True True False True
True 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')

FAIPS, DPS Kuwait Page 9 / 20 ©Bikram Ally


Python Notes Class XI Condition
Outer else contains inner if-else. If outer if condition is True, then 'Error: marks out of
range' will be displayed. If outer if condition is False, 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-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!')

Few functions from the math module


To use functions from the math module, math module has to be imported first. Calling a math module
function without importing math module will flag syntax error. Functions from math module are invoked
as math.function(parameter). Functions from math module are explained using Python shell IDLE.
Function name Use of the function
math.pi Represents mathematical constant 3.15159.
math.e Represents mathematical constant 2.71828.
math.log(x) Returns logarithm of a positive number x to the base e (e is 2.71828).
math.log10(x) Returns logarithm of a positive number x to the base 10.
math.sin(x) Returns sine of an angle x radians.
math.cos(x) Returns cosine of an angle x radians.
math.tan(x) Returns tangent of an angle x radians.
math.radians(x) Converts x degrees to radians.
math.gcd(a,b,c…) Returns HCF of at least two integers. Function will also accept zero and
negative integers as parameters.
math.lcm(a,b,c,…) Returns LCM of at least two integers. Function will also accept zero and
negative integers as parameters.
math.sqrt(x) Returns square root of number x if x is non-negative. If x is negative then
function triggers a run-time error.
math.pow(x,n) Returns x raised to the power n. If x raised to n cannot be calculated, then
function triggers a run-time error.
math.floor(x) Returns closest integer value which is less than or equal to x (given value).
The function will also accept zero and negative value as parameter.
math.ceil(x) Returns closest integer value which is greater than or equal to x (given value).
The function will also accept zero and negative value as parameter.
math.factorial(n) Returns factorial of a number n. Parameter n must be a non-negative integral
value (either 5 or 5.0 but not 5.3).
math.perm(n,r) Returns nPr as n!/(n-r)!, where n and r are non-negative integers.
math.comb(n,r) Returns nCr as n!/(n-r)/r!= nPr/r!, where n and r are non-negative integers.
FAIPS, DPS Kuwait Page 11 / 20 ©Bikram Ally
Python Notes Class XI Condition
>>> math.gcd(25,15)
Displays error message because gcd() is called without importing math module
>>> import math #imports math module
>>> math.gcd(25,15)
5
>>> math.gcd(8,24)
8
>>> math.gcd(28,7)
7
>>> math.gcd(5,7)
1
>>> math.gcd(10,0)
10
>>> math.gcd(-10,0)
10
>>> math.gcd(-4,-12)
4

>>> math.factorial(5) #Product of 1*2*3*4*5


120
>>> math.factorial(5.0) #Product of 1.0*2.0*3.0*4.0*5.0
120
>>> math.factorial(5.2)
Displays error message.
>>> math.factorial(-5)
Displays error message.

>>> 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.log(math.e**5) #log of e**5 to the base e


5.0
>>> math.log(math.e**0.5) #log of e**0.5 to the base e
0.5
>>> math.log(0)
Displays error message.
>>> math.log(-2.71828)
Displays error message.

FAIPS, DPS Kuwait Page 12 / 20 ©Bikram Ally


Python Notes Class XI Condition
>>> math.log10(1000)
3.0
>>> math.log10(100)
2.0
>>> math.log10(50)
3.912023005428146
>>> math.log10(0)
Displays error message.

>>> math.log10(-10)
Displays error message.

>>> math.sin(30) #sine of 30 radians


-0.9880316240928618
>>> math.sin(math.radians(30)) #sine of 30 degrees
0.49999999999999994
>>> math.sin(math.pi/6) #sine of 30 degrees
0.49999999999999994
>>> math.sin(math.radians(90)) #sine of 00 degrees
1.0

>>> math.cos(60) #cosine of 60 radians


-0.9524129804151563
>>> math.cos(math.radians(60)) #cosine of 60 degrees
0.5000000000000001
>>> math.cos(math.pi/3) #cosine of 60 degrees
0.5000000000000001
>>> math.cos(math.radians(0)) #cosine of 0 degrees
1.0

>>> math.tan(45) #tangent of 45 radians


1.6197751905438615
>>> math.tan(math.radians(45)) #tangent of 45 degrees
0.9999999999999999
>>> math.tan(math.pi/4) #tangent of 45 degrees
0.9999999999999999

>>> math.radians(30), math.pi/6 #30 degrees is pi/6 radians


(0.5235987755982988, 0.5235987755982988)

Examples of math.floor() and math.ceil()


from math import floor, ceil
>>> print(floor(12.8), ceil(12.8))
Displays 12 13
>>> print(floor(12.3), ceil(12.3))
Displays 12 13
>>> print(floor(12.5), ceil(12.5))
Displays 12 13
>>> print(floor(12), ceil(12))
Displays 12 12

>>> print(floor(-12.8), ceil(-12.8))


Displays -13 -12

FAIPS, DPS Kuwait Page 13 / 20 ©Bikram Ally


Python Notes Class XI Condition
>>> print(floor(-12.3), ceil(-12.3))
Displays -13 -12
>>> print(floor(-12.5), ceil(-12.5))
Displays -13 -12
>>> print(floor(-12), ceil(-12))
Displays -12 -12

Few methods (functions of string objects)


To use a function of str object either we should have a str (string) literal or we should have a str (string)
object (variable). We will assume that the string object (variable) or the string literal contains single
character. Functions of str object (variable) are invoked as str.function(). Functions from str object
(variable) are explained using Python shell IDLE.
Function name Use of the function
str.upper() Returns a string converted to uppercase. Only lowercase is converted to uppercase.
str.lower() Returns a string converted to lowercase. Only uppercase is converted to lowercase.
str.isupper() Check whether the string contains uppercase. True if str is uppercase.
str.islower() Check whether the string contains lowercase. True if str is lowercase.
str.isalpha() Check whether the string contains either uppercase or lowercase. True if str is either
uppercase or lowercase.
str.isdigit() Check whether the string contains digit. True if str is digit.
str.isalnum() Check whether the string contains either alphabet or digit. True if str is either
alphabet or digit. False if str is a special characters.
All the functions mentioned above also work with mult-characters string (string containing at least two
characters). We will discuss these functions when we will learn list (Second Term).

>>> c1, c2, c3, c4='D', 'b', '6', '*'


>>> c1.upper(), c2.upper(), c3.upper(), c4.upper()
('D', 'B', '6', '*')
>>> 'X'.upper(), 'p'.upper(), '2'.upper(), '$'.upper()
('X', 'P', '2', '$')

>>> c1.lower(), c2.lower(), c3.lower(), c4.lower()


('d', 'b', '6', '*')
>>> 'X'.lower(), 'p'.lower(), '2'.lower(), '$'.lower ()
('x', 'P', '2', '$')

>>> c1.isupper(), c2.isupper(), c3.isupper(), c4.isupper()


(True, False, False, False)
>>> 'X'.isupper(), 'p'.isupper(), '2'.isupper(), '$'.isupper()
(True, False, False, False)

>>> c1.islower(), c2.islower(), c3.islower(), c4.islower()


(False, True, False, False)
>>> 'X'.islower(), 'p'.islower(), '2'.islower(), '$'.islower ()
(False, True, False, False)

>>> c1.isalpha(), c2.isalpha(), c3.isalpha(), c4.isalpha()


(True, True, False, False)
>>> 'X'.isalpha(), 'p'.isalpha(), '2'.isalpha(), '$'.isalpha()
(True, True, False, False)

>>> c1.isdigit(), c2.isdigit(), c3.isdigit(), c4.isdigit()


(False, False, True, False)
FAIPS, DPS Kuwait Page 14 / 20 ©Bikram Ally
Python Notes Class XI Condition
>>> 'X'.isdigit(), 'p'.isdigit(), '2'.isdigit(), '$'.isdigit()
(False, False, True, False)

>>> c1.isalnum(), c2.isalnum(), c3.isalnum(), c4.isalnum()


(True, True, True, False)
>>> 'X'.isalnum(), 'p'.isalnum(), '2'.isalnum(), '$'.isalnum()
(True, True, True, False)

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.

Using not operator


>>> print(not 100, not 2.5, not -55, not -8.9, not 'DPS')
Displays False False False False False because not of non-zero value (True) or not of
non-empty string (True) is False.
>>> print(not 0, not 0.0, not '')
Displays True True True because not of zero (0 is False) or not of empty string ('' is False) is True.
Using or operator
>>> print(10 or 20 or 30, -50 or -60 or -70)
Displays 10 -50 because when all the values are non-zero (True), then the expression returns first non-
zero value from the left.
>>> print(5.6 or 4.5 or 3.8, -1.5 or -2.5 or -3.5)
Displays 5.6 -1.5 because when all the values are non-zero (True), then the expression returns first
non-zero value from the left.
>>> print('DPS' or 'KUWAIT' or 'FAIPS')
Displays DPS because when all the values are non-empty string (True), then the expression returns first
non-empty string from the left.

>>> print(100 or 3.8 or 'DPS')


Displays 100 because when all the values are either non-zero value (True) or non-empty string (True),
then the expression returns first true value from the left.
>>> print(3.8 or 'DPS' or 100)
Displays 3.8 because when all the values are either non-zero value (True) or non-empty string (True),
then the expression returns first true value from the left.
>>> print('DPS' or 100 or 3.8)
Displays DPS because when all the values are either non-zero value (True) or non-empty string (True),
then the expression returns first true value from the left.

>>> print(0 or 20 or 30, -0 or -60 or -70)


Displays 20 -60 because the expression returns first non-zero value from the left.
>>> print(0 or 0 or 30, -0 or -0 or -70)
Displays 30 -70 because the expression returns first non-zero value from the left.
>>> print(0 or 20 or 0, -0 or -60 or -0)
Displays 20 -60 because the expression returns first non-zero value from the left.
>>> print(10 or 20 or 0, -50 or -60 or -0)
Displays 10 -50 because the expression returns first non-zero value from the left.
>>> print(0 or 0 or 0, -0 or -0 or -0)
Displays 0 0 since all conditions are zero (0 is False).

>>> print('' or 'KUWAIT' or 'FAIPS')


Displays KUWAIT because the expression returns first non-empty string from the left.
>>> print('' or '' or 'FAIPS')
Displays FAIPS because the expression returns first non-empty string from the left.
>>> print('' or 'KUWAIT' or '')
Displays KUWAIT because the expression returns first non-empty string from the left.
>>> print('DPS' or 'KUWAIT' or '')
Displays DPS because the expression returns first non-empty string from the left.
>>> print('' or '' or '')
Displays empty string (not visible on the screen) since all conditions are empty string ('' is False).
FAIPS, DPS Kuwait Page 17 / 20 ©Bikram Ally
Python Notes Class XI Condition
Note: when using or operator, at least one condition is True, means entire if condition is True. So, if
the first condition from the left is True, means Python will not check remaining conditions.
Using and operator
>>> print(10 and 20 and 30, -50 and -60 and -70)
Displays 30 -70 because when all the values are non-zero (True), then the expression returns first non-
zero value from the right.
>>> print(5.6 and 4.5 and 3.8, -1.5 and -2.5 and -3.5)
Displays 3.8 -3.5 because when all the values are non-zero (True), then the expression returns first
non-zero value from the right.
>>> print('DPS' and 'KUWAIT' and 'FAIPS')
Displays KUWAIT because when all the values are non-empty string (True), then the expression returns
first non-empty string from the right.

>>> print(0 and 20 and 30, -0 and -60 and -70)


Displays 0 0 because at least one value is zero (False) means, expression returns zero (0 is False).
>>> print(10 and 0 and 30, -50 and -0 and -70)
Displays 0 0 because at least one value is zero (False) means, expression returns zero (0 is False).
>>> print(0 and 20 and 0, -0 and -0 and -70)
Displays 0 0 because at least one value is zero (False) means, expression returns zero (0 is False).
>>> print(0 and 0 and 0, -0 and -0 and -0)
Displays 0 0 because all values are zero (False) means, expression returns zero (0 is False).
>>> print(10 or 0 and 30, (0 or 20) and 30, 10 and 20 or 0)
Displays 10 30 20

>>> print('' and 'KUWAIT' and 'FAIPS')


Displays empty string (not visible on the screen) because at least one value is an empty string (False)
means, expression returns empty string ('' is False).
>>> print('DPS' and '' and 'FAIPS')
Displays empty string (not visible on the screen) because at least one value is an empty string (False)
means, expression returns empty string ('' is False).
>>> print('DPS' and '' and '')
Displays empty string (not visible on the screen) because at least one value is an empty string (False)
means, expression returns empty string ('' is False).
>>> print('' and '' and '')
Displays empty string (not visible on the screen) because all values are empty string (False) means,
expression returns empty string ('' is False).

>>> print(10 and 7.3 and '')


Displays empty string (not visible on the screen) because at least one value is False (empty string)
means, expression returns False (empty string).
>>> print(0 and 7.3 and 'DPS')
Displays 0 because at least one value is False (zero) means, expression returns False (zero).
>>> print(10 and 0.0 and 'DPS')
Displays 0.0 because at least one value is False (zero) means, expression returns False (zero).
>>> print(0 and '', '' and 0.0)
Displays 0 empty string (not visible on the screen) because expression returns first zero (False) / empty
string (False) from the left when the expression contains only False (zero values or empty strings).

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).

Special logical expressions of Python


Conventional way of writing logical expression Python way of writing logical expression
>>> a, b, c=10, 10, 10 >>> a, b, c=10, 10, 10
>>> print(a==b and b==c) >>> print(a==b==c)
Displays True Displays True
>>> print(a!=b and b!=c and c!=a) >>> print(a!=b!=c!=a)
Displays False Displays False
>>> a, b, c=100.5, 100.5, 100.5 >>> a, b, c=100.5, 100.5, 100.5
>>> print(a==b and b==c) >>> print(a==b==c)
Displays True Displays True
>>> print(a!=b and b!=c and c!=a) >>> print(a!=b!=c)
Displays False Displays False
>>> ch1, ch2='T', '*' >>> ch1, ch2='T', '*'
>>> print(ch1>='A' and ch1<='Z') >>> print('A'<=ch1<='Z')
Displays True Displays True
>>> print(ch2>='A' and ch2<='Z') >>> print('A'<=ch2<='Z')
Displays False Displays False
>>> ch1, ch2='r', '*' >>> ch1, ch2='T', '*'
>>> print(ch1>='a' and ch1<='z') >>> print('a'<=ch1<='z')
Displays True Displays True
>>> print(ch2>='a' and ch2<='z') >>> print('a'<=ch2<='z')
Displays False Displays False
>>> ch1, ch2='5', '*' >>> ch1, ch2='5', '*'
>>> print(ch1>='0' and ch1<='9') >>> print('0'<=ch1<='9')
Displays True Displays True
>>> print(ch2>='0' and ch2<='9') >>> print('0'<=ch2<='9')
Displays False Displays False
>>> th1, th2, th3=56, 80, -20 >>> th1, th2, th3=56, 80, -20
>>> print(th1>=0 and th1<=70) >>> print(0<=th1<=70)
Displays True Displays True
>>> print(th2>=0 and th2<=70) >>> print(0<=th2<=70)
Displays False Displays False
>>> print(th3>=0 and th3<=70) >>> print(0<=th3<=70)
Displays False Displays False

Use of parameter sep with print() function


>>> print(10, 'ABHAY', 98.5)
Displays 10 ABHAY 98.5 since default separator in a print() function is single space (' '). By
using the parameter sep with print() function, one can change the default separator to some other
character(s). Few examples are given below:
>>> print(10, 'ABHAY', 98.5, sep='#')
Displays 10#ABHAY#98.5 since default separator space (' ') is replace by '#'.
>>> print(10, 'ABHAY', 98.5, sep=':')
Displays 10:ABHAY:98.5 since default separator space (' ') is replace by ':'.
>>> print(10, 'ABHAY', 98.5, sep='->')
Displays 10->ABHAY->98.5 since default separator space (' ') is replace by '->'.
>>> print(10, 'ABHAY', 98.5, sep='<-->')
Displays 10<-->ABHAY<-->98.5 since default separator space (' ') is replace by '<-->'.
>>> print('FAIPS', sep='*****')

FAIPS, DPS Kuwait Page 19 / 20 ©Bikram Ally


Python Notes Class XI Condition
Displays FAIPS since parameter sep does not play any role when only one data item to be displayed
by the print() function. Parameter sep will only come into play when two or more data items are to
displayed by the print() function. All the data items are to be separated by the same character(s)
when parameter sep is used with the print() function.

Use of parameter end with print() function


>>> a=10
>>> b=20
>>> print(a, b)
Displays 10 20
>>> a, b=10, 20
>>> print(a, b)
Displays 10 20
>>> a=10; b=20; #Multiple statements on the same row separated by ;
>>> print(a, b)
Displays 10 20
>>> a=10; b=20; print(a, b)
Displays 10 20

>>> print('FAIPS'); print('DPS'); print('Kuwait')


Displays
FAIPS
DPS
Kuwait
Since by default second print() function displays DPS from the beginning of the next row (line) and
third print() function displays DPS from the beginning of the next row (line). But using parameter
end with print() function one can control the position, where second print(), third print()
function … will display its output. Few examples are given below:
>>> print('FAIPS', end=' '); print('DPS', end=' '); print('Kuwait')
Displays FAIPS DPS KUWAIT because end=' ' in the first print() function and in the second
print() will display the three data items on the same row (line) separated by space. Since
print('Kuwait') is the last print() function, no need for parameter end.
>>> print('FAIPS', end='->'); print('DPS', end='->'); print('Kuwait')
Displays FAIPS->DPS->KUWAIT

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

FAIPS, DPS Kuwait Page 20 / 20 ©Bikram Ally

You might also like