0% found this document useful (0 votes)
15 views30 pages

DMPP Selection Mathematical Functions

Uploaded by

motwanilakshya98
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)
15 views30 pages

DMPP Selection Mathematical Functions

Uploaded by

motwanilakshya98
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/ 30

Selection and Mathematical

Functions
MDI Gurgaon

1
Agenda
● Relational Operators
● Random number (basic intro to module)
● If-the-else variants
● Logical Operators
● Match case
● Math functions
● strings and associated utilities
● Examples and Discussion

2
Relational Operators
● A Boolean expression is an expression that evaluates to True or False

3
Boolean Type
● A Boolean variable as you already know can store True or False
● GameOn = True
● print(GameOn)
● True
● print(int(GameOn))
● 1
● print(bool(0))
● False
● print(bool(6))
● True
● # prints False for 0 and True for all other values

4
Generating Simple Random Numbers
● The randint(a,b) function within module random can generate a random integer
between a and b
● import random
● a = random.randint(6,12)
● a
● 9
● # use randrange(a,b) to generate a random number between a and b-1
● b = random.randrange(6,12)
● b
● 10
● c = random.random() # a random value between 0 and 1
● c
● 0.5259557578412462
5
Selection via simple if statement
● a=9
● if a % 3 ==0:
● print(a, "is Divisible by 3")

● 9 is Divisible by 3
● A simple if can be used multiple times to check specific conditions depending
upon the context

6
Selection via if then else statement
● a =5
● if a % 3 ==0:
● print(a, "is Divisible by 3")
● else:
● print(a, "is not Divisible by 3")

● 5 is not Divisible by 3
● An if-then-else enables division of the world into two exclusive parts !!
● It is not necessary that if may be followed by else as we have seen the simple
if in previous slide

7
Selection via nested if then else statement
● Best examples are either grading of students ● #format 2
in a exam or computation of tax etc, comes
in two different formats
● if marks1 > 90 :
● marks1 = 78 ● print('grade is A')
● if marks1 > 90 : ● elif marks1 > 80 :
● print('grade is A') ● print('grade is B')
● else:
● if marks1 > 80 :
● elif marks1 > 70 :
● print('grade is B') ● print('grade is C')
● else: ● elif marks1 > 60 :
● if marks1 > 70 : ● print('grade is D')
● print('grade is C')
● else: ● else:
● if marks1 > 60 : ● print('grade is F')
● print('grade is D') ●
● else: ● grade is C
● print('grade is F')

● 8
● grade is C
Logical Operators
● The logical operators not, and, or are used for creating compound Boolean
expressions
● # Receive an input
● number = int(input("enter an integer:"))

● if number % 2 ==0 and number % 3 == 0 :
○ print (number, "is divisible by 2 and 3")

● if number % 2 ==0 or number % 3 == 0 :
○ print (number, "is divisible by 2 or 3")

● if (number % 2 ==0 or number % 3 == 0) and \
not (number % 2 ==0 and number % 3 == 0) :
○ print (number, "is divisible by 2 or 3 but not both 2 and 3") 9
Implement Case Study : Computing Taxes : In class

● Please use the simple Indian Income Tax slab to calculate tax for three
different values of salary
● Income Tax Slabs Under New Tax Regime for FY 2023-24, FY 2024-25
● Range of Income (Rs.) Tax Rate
● Upto 3,00,000 Nil
● 3,00,000-6,00,000 5%
● 6,00,000-9,00,000 10%
● 9,00,000-12,00,000 15%
● 12,00,000-15,00,000 20%
● Above 15,00,000 30%
● As a follow-up exercise, use old tax regime and compare the tax, can you
make the person choose new vs old tax slab as well??

10
Match-case statement

● Match case statement are a specific format of if-then -else


family where an expression when evaluated can lead to
different processing
● The syntax is given by :
● match expression:
○ case value1: statement1
○ case value2: statement2
○ ………….
○ case valuen: statementn
○ case _: statement for default case

11
Example
● def testmatch(x):
● match x:
● case 1: print(x,'single')
● case 2: print(x*x,'square')
● case 3: print(x**3,'cube')
● case _: print('check the input')


● testmatch(5)
● check the input
● testmatch(2)
● 4 square
● testmatch(3)
● 27 cube
● testmatch(0)
● check the input 12
Assignment_2a

● Attempt 3.11, 3.15, 3.18, 3.19, 3.21, 3.23, 3.26, 3.29, 3.33, 3.34

13
Understanding eval()
● In Python eval() can be used to get the output from an string based
expression but not compound statements or assignments
● String is parsed, compiled to bytecode and evaluated
● The syntax is eval(expression,[global,[local]]), the optional arguments are held
as dictionaries and may not be required
● "28 * 28"
● '28 * 28'
● eval('28 * 28')
● 784
● x=12
● eval('x**2')
● 144

14
More on eval()

● eval('x+y',{'x':100},{'y':200})
● 300
● x=100
● y=200
● eval('x+y')
● 300

15
Mathematical Functions
● Python provides a plethora of mathematical functions for common tasks

Function Function Function Function

abs(x) round(x) floor(x) sqrt(x)

max(x1..) round(x,n) exp(x) hypot(x,y)

min(x1…) fabs(x) log(x) sin(x)

pow(a,b) is a^b ceil(x) log(x,base) cos(x)

asin(x) acos(x) tan(x) degrees(x)

radians(x)

16
Strings and Characters
● A string is a sequence of characters, while a character is considered as a
string with just one element
● Every individual character is mapped to its binary representation using a
character encoding of specific nature, prominent one is ASCII, 8 bit scheme,
for all characters in english language
● ASCII uses numbers 0 to 127 to represent characters
● Unicode is a comprehensive scheme which includes ASCII codes, but
includes many other languages
● Represented as \u followed by four hexadecimal digits running from \u0000 to
\uFFFF
● In Python ord() and chr() are the functions to convert to ASCII code and back

17
Escape Sequence
● For printing special characters either triple quotes (‘’’ ‘’’) could be used or a
more well known way is the use of escape sequences
● Escape sequence is a special notation that comprises a “\” followed by a
character/s
● print('he says the best way to remember OSI layers is \"All People Should Try
New Data Processing\"')
● he says the best way to remember OSI layers is "All People Should Try New
Data Processing"
● print('\\b is a backspace')
● \b is a backspace
● Others are \r, \f, \t

18
String utilities
● The str() converts numeric, boolean ● Reading input from console
and any other format to string type ● a1 = input("enter an integer: ")
● str(8.89) ● enter an integer: 23
● '8.89' ● a1
● str(4+6j) ● '23'
● '(4+6j)' ● s1 = "Baadshah o Baadshah"
● 'shah' in s1
● s1 = 'hello'
● True
● s2 = 'stranger' ● 'Bad' in s1
● s1+s2 ● False
● 'hellostranger' ● 'baad' in s1
● s1+" "+s2 ● False
● 'hello stranger' ● 'Baad' in s1
● s3 = 3*s1 ● True
● s3 ● 'Bad' not in s1
● 'hellohellohello' ● True
19
String utilities
● Index operator [ ] is used for accessing
● Comparing strings is individual characters in a string
● S[index]
accomplished by using ASCII ● s2 = 'virat kohli'
● s2[0]
codes as the basis ● 'v'
● 'tendulkar' > 'dravid' ● s2[2]
● 'r'
● True ● s2[-1]
● 'i'
● 'Sachin' < 'rahul' ● s2[0:5]
● True ● 'virat'
● s2[7:-1]
● Other utilities include len(), max() ● 'ohl'
● s2[6:]
and min() ● 'kohli'
● s2[:5]
● 'virat'
● s2[6:12]
● 'kohli'
20
String utilities
● Some other utilities available in ● s2 = 'virat kohli'
Python ● s2.upper()
● lower() ● 'VIRAT KOHLI'
● upper() ● s2.isspace()
● isupper() ● False
● islower() ● '2012'.isdigit()
● True
● isdigit()
● s3 ='1234abc'
● isalnum()
● s3.isalnum()
● isalpha()
● True
● isidentifier()

21
String utilities
● Some other utilities available in ● s2 = 'virat kohli'
Python ● s2.capitalize()
● capitalize() ● 'Virat kohli'
● title() ● s2.title()
● swapcase() ● 'Virat Kohli'
● replace(old,new) ● s2.swapcase()
● 'VIRAT KOHLI'
● replace(old,new,n)

22
String utilities
● Some search and count related ● s1 = 'starboard is right'
utilities available in Python are ● s1.startswith('star')
● endswith(s) ● True
● startswith(s) ● s1.endwith('ght')
● find(s) ● True
● rfind(s) ● s1.find('boa')
● 4
● count(substring)
● s1.rfind('r')
● 13
● s1.count('a')
● 2

23
String Utilities
● The characters ‘ ‘,,\t,\b,\r, and \n ● The groups are encouraged to
are called the whitespace understand the logic of the Problem
characters Guessing Birthdays as discussed in
Case 4.7
● The class str in Python contains
utilities that allow you to strip the
space on either left, right or on
either side
● lstrip()
● rstrip()
● strip()

24
Formatting Numbers
● Number formatting is a continuous ● The scientific notation can be
requirement for any display or usage specified by replacing ‘f’ in the
● Syntax is format specifier by an ‘e’
format(item,format-specifier), this ● print(format(23.45234,'10.3f'))
format is part of the print statement ● 23.452
● Format-specifier is the string ● print(format(23.45234,'10.3e'))
specifying precise display and
● 2.345e+01
precision requirements
● For percentage replace by ‘%’
● Format specifier itself is presented as
● print(format(0.4523,'10.3%'))
width.precisionf
● 45.230%
● print(format(23.67856,’8.4f’))

25
Formatting Numbers
● The numbers are right justified by ● The numbers could also be formatted
default, however, one coil duse ‘<’, into decimal, hexadecimal, octal or
‘>’, or ‘^’ to left justify, right justify or binary format by using specifiers
centered format d,x,o and b
● print(format(23.45234,'<10.3f')) ● print(format(7896,'10d'))
● 23.452 ● 7896
● print(format(7896,'10x'))
● print(format(23.45234,'^10.3f'))
● 1ed8
● 23.452
● print(format(7896,'10o'))
● print(format(23.45234,'>10.3f'))
● 17330
● 23.452
● print(format(7896,'10b'))
● 1111011011000
26
Formatting Strings
● F-strings starts with ‘f’ or ‘F’ and it may
● The conversion to string shall contain expression that are enclosed
require the end element of inside curly brackets
format-specifier to be set to s ● Expressions are evaluated in runtime
● x= 25
● print(format('Kalki 2898 is a fine
● y = 37
movie','50s')) ● f'the value of x is {x} and value of y is
● Kalki 2898 is a fine movie {y}'
● print(format('Kalki 2898 is a fine ● 'the value of x is 25 and value of y is
37'
movie','>50s')) ● f'the value of x is {x:5.2f} and value of
● Kalki 2898 is a y is {y:5.2e}'
fine movie ● 'the value of x is 25.00 and value of y
is 3.70e+01'

27
Assignment_2b

● Attempt the following


● 4.2,4.3,4.21,4.22, 4.24, 4.28,
4.32, 4.37

28
Thanks
Q and A!!!

29
References
● Sridhar,S., Indumathi,J., Hariharan, V.M., “Python Programming”, Pearson,
2023, First Impression
● Liang, Y.D., “Introduction to Python Programming and Data Structures”,
Pearson, Third Edition, Second Impression, 2024
● Bibliography
● Python eval(): Evaluate Expressions Dynamically

30

You might also like