Unit 2 MDM.pptx.........................

bhaktikundhare 0 views 138 slides Oct 13, 2025
Slide 1
Slide 1 of 138
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138

About This Presentation

Python chapter 2


Slide Content

Unit-2 Variables, operations, Control flow – assignments, conditionals Loops Functions: optional arguments, default values, passing functions as arguments. 1

Variables in Python What is a Variable? A variable is a name that refers to a value stored in memory. It allows you to store and reuse data in your program. How to Create a Variable: name = "Alice" # string age = 25 # integer height = 5.6 # float is_student = True # Boolean 2

Variables in Python Explanation: name holds a string "Alice" age holds an integer 25 height holds a floating-point number 5.6 is_student holds a boolean value True Python automatically understands the data type, so you don’t need to declare it explicitly. 3

Python Operators — Variables in Python What is a Variable? A variable is a name that refers to a value stored in memory. It allows you to store and reuse data in your program. How to Create a Variable: name = "Alice" # string age = 25 # integer height = 5.6 # float is_student = True # boolean Explanation: name holds a string "Alice" age holds an integer 25 height holds a floating-point number 5.6 is_student holds a boolean value True Python automatically understands the data type, so you don’t need to declare it explicitly. 4

Python Operators — Operators are used to perform operations on variables and values. — Python divides the operators in the following groups: Arithmetic operators Assignment operators Unary minus operator Comparison (Relational) operators Logical operators — Boolean operators Bitwise operators — Membership operators Identity operators 5

1. Arithmetic Operators — Arithmetic operators are used to perform arithmetic operations like addition, subtraction, multiplication, etc. — There are seven arithmetic operators available in Python. — Let's assume x = 5 and y = 2. — Also called ‘binary operators’ as operates on two variables only. 6 Operator Description Example Result + Addition (Adds two values) x+y 7 - Subtraction (Subtract right operator from left operator) x-y 3 * Multiplication (Multiply two values) x*y 10

1. Arithmetic Operators 7 Operator Description Example Result / Division (Divide left by right operator) x/y 2.5 // Floor Division or Integer division (Gives only integer quotient after division.) x//y 2 % Modulus operator (Gives remainder of division) x % y 1 ** Exponentiation (Calculate exponential value a to the power b) x ** y 25 / Division (Divide left by right operator) x/y 2.5

1. Arithmetic Operators — When there is an expression contains several arithmetic operators, then following order of evaluation is used: 1. Parentheses 2. Exponentiation 3. Multiplication, division, modules and floor divisions 4. Addition and subtraction 5. Assignment operation — 8 For example d = (1+2) * 3 ** 2 // 2+3 d = 3 * 3 ** 2 // 2+3 = 3 * 9 // 2 + 3 = 27 // 2 +3 = 13 +3 d = 16

2. Assignment Operators — These operators are used to assign (or store) right side value into left side variable. — Can also be used to perform simple arithmetic operations also. 9 Operator Description Example Result = x=5 x=5 5 + = x +=3 x= x+3 8 - = x -=3 x= x-3 2 * = x*=3 x= x*3 15 / = x/= 3 x= x/3 1.66 % = x%=3 x=x%3 2 // = x//=3 x= x//3 1

3. Unary Minus Operator — The unary minus operator is denoted by the symbol minus (-). — When this operator is used before a variable, its value is negated. — Means it converts positive value into negative and vice versa. — For example: n = 10; print (-n) -10 num = -10 print (-num) 10 10

5. Logical Operators and, or ,not We can apply for all types. For boolean types behaviour: and ==>If both arguments are True then only result is True or ====>If atleast one arugemnt is True then result is True not ==>complement True and False ==>False True or False ===>True not False ==>True 11

5. Logical Operators For non-boolean types behaviour: 0 means False non-zero means True empty string is always treated as False 12

5. Logical Operators x = 100 y = 200 13 Operator Description Example Result and If x is False returns x, else returns y x and y 200 If y is False returns y, else returns x y and x 100 or If x is False returns y, else returns x x or y 100 If y is False returns x, else returns y y or x 200 not If x is false, returns True, else returns False not x False not y False

5. Logical Operators If x and y are boolean x=True y= False 14 Operator Description Example Result and Boolean and operator. If both x and y are True, then it returns True, else returns False. x and y False or Boolean and operator. If x or y are True, then it returns True, else returns False. (OR it returns False if both x and y False, else returns True) x or y True not Boolean not operator. If x is True, it returns False, else returns True. not x False not y True

6. Bitwise Operators — These operators operate on individual bits 0 and 1. — When used on integer (decimal), octal or hex numbers, then convert it into binary, performs bitwise operation and then converts back to integer again and prints result as integer number. — For example, x = 10 = 0000 1010 and y = 11 = 0000 1011, 15 Operator Description Example Result ~ Bitwise Complement (tilde) ~10 -11 & Bitwise AND (ampersand) x & y 10 | Bitwise OR (pipe) x | y 11 ^ Bitwise XOR (cap/carat/circumflex) x ^ y 1 << Bitwise LEFT SHIFT (double less than) x<<2 40 >> Bitwise RIGHT SHIFT (double greater than) x>>2 2

7. Membership Operators — The membership operators are useful to test for membership in a sequence such as strings, lists, tuples or dictionaries. — For example, a list x = [“apple”, “banana”, “mango”, “pineapple”] 16 Operator Description Example Result in If a sequence with the specified value is present in the object, returns True, else returns false. print("banana" in x) True False print("cherry" in x) not in If a sequence with the specified value is not present in the object, returns True, else returns false. print("banana" not in x) False

8. Identity Operators — These operators compare the memory locations of two objects, to know that they are same or not. — Memory location of an object can be seen using id() function, which returns an integer number called identity number that internally represents the memory location of the object. — For example, a,b,c = 25,25,35 id(a) 140733546416544 id(b) 140733546416544 id(c) 140733546416864 17

8. Identity Operators x = [1,2,3,4] y = [1,2,3,4] id(x) 2995869694912 id(y) 2995877358016 18

8. Identity Operators 19 Operator Description Example Result is If the identity numbers of the objects are same, returns True, else returns false. a is b True a is c False x is y False is not If the identity numbers of the objects are not same, returns True, else returns false. a is not b False a is not c True x is not y True

Precedence of Operators — An expression or formula may contain several operators. — In such case programmer should know which operator is to be executed first and which one to be executed next. — The sequence of operation of the operators is called operator precedence. — Precedence represents the priority level of the operator. The operator with the high precedence will be executed first. 20

Precedence of Operators 21 Operator Name ( ) Parenthesis ** Exponentiation -,~ Unary Minus, Bitwise Complement *,/,//,% Multiplication, Division, Floor Division, Modules +,- Addition, Subtraction <<,>> Bitwise left shift, Bitwise right shift & Bitwise And

22 Operator Name ^ Bitwise XOR | Bitwise Or >,>=,<,<=<,==,!= Relational Operators =,%=,/=,//=,-=,+= Assignment Operators is, is not Identity Operators in, not in Membership Operators not Logical Not or Logical Or

Data Types Let's understand data types with an example: Suppose you have some data i.e. ON & OFF then you can save this data in ……. Boolean data type but what if your data ranges from 1 to 10, then you need to use integer data types instead of Boolean . 23

Data Types Python Data Types: A data type is a classification of data that informs the compiler or interpreter how a programmer intends to use the data. There are numerous data types available in python, which we can use depending on our projects' requirement . 24

Data Types Data Type represent the type of data present inside a variable. In Python we are not required to specify the type explicitly. Based on value provided, the type will be assigned automatically. Hence Python is Dynamically Typed Language. 25

Data Types Python contains the following inbuilt data types 1. int 2. float 3. complex 4. bool 5. str 6. range 7. list 08. tuple 09. set 10. frozenset 11. dict 12. None 26

Data Types Numeric Types: int , float , complex Sequence Types: String, list , tuple , range Mapping Type: dict Set Types: set , frozenset Boolean Type: bool None Type: NoneType 27

Numeric data types Data that has a numeric value is represented by Numeric data type A numeric value can be an integer, a floating number, or even a complex number. These values are defined as Python int , Python float , and Python complex classes in Python . 28

Numeric data types Integers – It contains positive or negative whole numbers (without fractions or decimals). In Python, there is no limit to how long an integer value can be. Float – It is a real number with a floating-point representation . It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation. Complex Numbers – It is specified as (real part) + (imaginary part)j . For example – 2+3j 29

Numeric data types a = 5 print("Type of a: ", type(a)) b = 5.0 print("\nType of b: ", type(b)) c = 2 + 4j print("\nType of c: ", type(c)) Type of a: <class 'int'> Type of b: <class 'float'> Type of c: <class 'complex'> 30

2. Sequence data types The sequence Data Type in Python is the ordered collection of similar or different Python data types. Sequences allow storing of multiple values in an organized and efficient fashion. There are several sequence data types of Python: String List Tuple Range 31

2.1 : String (Sequence data types) A string is a collection of one or more characters put in a single quote, double-quote, or triple-quote. In Python, there is no character data type In Python, a character is a string of length one. It is represented by str class. 32

2.1 : String (Sequence data types) Creating strings: >>> s1 = ‘Welcome’ # Enclose string inside a single quote >>> s2 = “Welcome” # Same as using double quote >>> s3 = ‘’’Welcome to Python programming. This subject covers all the basics for Python programming language.’’’ >>> s4 = “””Welcome to Python programming. This subject covers all the basics for Python programming language.””” Use triple single quotes or double quotes to create strings with multiple lines. 33

2.1 : String (Sequence data types) Creating strings: s1 = 'Welcome' # Enclose string inside a single quote. s2 = "Welcome" # Same as using double quote. s3 = '''Welcome to Python programming. This subject covers all the basics for Python programming language.‘ ''s4 = """Welcome to Python programming. This subject covers all the basics for Python programming language.""“ print(s1) print(s2) print(s3) print(s4) Use triple single quotes or double quotes to create strings with multiple lines. 34

2.1 : String (Sequence data types) Substring: Smaller portion inside a string which we want to highlight. For example, “Welcome to Core Python programming” It is possible to display quotation marks to mark a substring in a string. >>> a= “Welcome to ‘Core Python’ programming” >>> print (a) Welcome to ‘Core Python’ programming 35

2.1 : String (Sequence data types) >>> b= ‘Welcome to “Core Python” programming’ >>> print (b) Welcome to “Core Python” programming 36

2.1 : Properties String (Sequence data types) Length of a string Length of a string represents the number of characters in a string. To know the length of a string, we can use len() function. This function gives number of characters including spaces. >>> a= ‘core python’ >>> n = len(a) >>> print(n) 37

2.1 : Properties String (Sequence data types) Strings are immutable Immutable object is an object whose contents cannot be changed. On the other hand mutable object means object whose contents can be changed. In Python, numbers, strings and tuples are immutable, whereas lists, sets and dictionaries are mutable. 38

2.1 : Properties String (Sequence data types) Strings are immutable Example: >>> s1 = ‘one’ # create first string >>> s2 = ‘two’ # create second string >>> s2 = s1 # Assign s1 to s2 >>> print (s2) 39

2.1 : Properties String (Sequence data types) It seems that contents of s2 is replaced by s1 and hence s2 became mutable. But this is wrong. When we write s2 = s1, s2 has adjusted to refer the object referred by s1, i.e. one and as two is not referred by any variable is removed by garbage collector. 40

Control Statements — When we write program, the statements are normally executed one by one. This type of execution is called ‘Sequential Execution’. import math r=float(input('Enter a Radius: ‘)) area=math.pi*r**2 print("Area of a Circle: ",area) — Sequential execution is suitable for only simple programs. — It is not suitable for developing critical programs where complex logic is needed. 41

Need of Control Statements — To develop critical programs ,the programmer should be able to change the flow of execution as needed by him. —For example the programmer may wish to repeat the group of statements several times or he may want to directly jump from one statement to another statement in program . — For this purpose we need control statements in the program. 42

Control Statements — if statements — if…else statement — if…elif…else statement — while loop — for loop — break statement — continue statement — pass statement — return statement 43

If statement — This statement is used to execute one or more statements depending on whether a condition is true or not. — The syntax of if statement is given below: if condition: statements First the condition is tested. If the condition is True, then the statements given after colon(:) are executed. We can write one or more statements after colon(:) . If the condition is false, then the statements mentioned after colon are not executed. 44

A word on Indentation and nested if — Understanding indentation is very important in Python. — Indentation refers to spaces (generally 04 spaces) that are used in the beginning of statement. — The statements with same indentation belong to same group called suite . For example, if x == 1: print (‘a’) print(‘b’) if y == 2: print (‘c’) print (‘d’) print (“end”) 45 Output when x=1, y=0 Output when x=2, y=2 Output when x=1, y=2 ??? ??? ???

If else statement — The if…else statement executes group of statements when a condition is True ; otherwise it will execute another group of statements. — The syntax of if….else statements is given below: if condition: statement1 (or suite 1) else: statement2 (or suite 2) — If the condition is true it will execute statement1 and if the condition is false it will execute statement2.It is advised to use four spaces as indentation before statement1 & statement2. 46

If else statement Take a input from user Write a python program to check whether number is even or odd Take a input from user and write python program to check number is divisible by 7 or not. Write a python program to display “Hello” if number entered is multiple of 5 else print “Bye” 47

Example x = int (input (“Enter the number: ”)) if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") 48 Enter the number: 41 Above ten, and also above 20! Enter the number: 15 Above ten, but not above 20

Shorthand Shorthand If — If you have only one statement to execute, you can put it on the same line as the if statement. if a > b: print("a is greater than b") Shorthand If ... Else • If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: a = 2 b = 330 print("A") if a > b else print("B") 49

If elif …..else — Sometimes the programmer has to test multiple condition and execute statements depending on those conditions. — if…elif…else statement is useful in such situation. — The syntax of if…elif…else statement is given below: if condition1: statement1 (or suite 1) elif condition2: statement2 (or suite 2) elif condition3: statement3 (or suite 3) else: statement4 (or suite 4) 50

If elif …..else — First condition1 is checked. When condition 1 is True , the statement1 will be executed. — If condition1 is False then condition2 is evaluated. When condition2 is True statement2 will be executed. — If condition2 is also False then condition3 is tested. When condition3 is True, then statement3 will be executed. — When condition3 is also False, the statement4 will be executed. It means statement4 will be executed if and only if none of the conditions are True. 51

52

If elif …..else (IMP) — A Python program to check whether a number is zero or positive or negative. x = int(input (“Enter a number:”)) if x==0: print(‘You entered Zero.’) elif x>0: print(x, ‘is a Positive number.’) else: print(x, ‘is a Negative number.’) 53 Enter a number: 0 You entered Zero. Enter a number: 11 11 is a Positive number. Enter a number: -5 -5 is a Negative number.

If elif …..else — For example, a program to find whether a number is even or odd. x = int(input(“Enter the no ”)) if x%2==0: print(x, ‘is an even number.’) else: print(x, ‘is an odd number.’) 54 OUTPUT: Enter the no 10 10 is an even number.

If elif …..else — A Python program to test whether a given number is in between 1 and 10. x= int(input('Enter a Number: ‘)) if x>=1 and x<=10: print(“You typed” ,x , “which is in between 1 & 10.”) else: print (“You typed” ,x , “which is not in between 1 & 10.”) 55 OUTPUT: Enter a number: 8 You typed 8 which is in between 1 and 10. Enter a number: 11 You typed 11 which is not in between 1 and 10.

If elif …..else — A Python program to accept a single digit number from keyboard (0 to 9) and display in words. x = int(input (“Enter a number:”)) if x==0: print(“ZERO”) elif x==1: print(“ONE”) elif x==2: print(“TWO”) elif x==3: print(“THREE”) elif x==4: print(“FOUR”) elif x==5: print(“FIVE”) elif x==6: print(“SIX”) elif x==7: print(“SEVEN”) elif x==8: print(“EIGHT”) elif x==9: print(“NINE”) # else part is not compulsory 56 OUTPUT: Enter a number: 0 ZERO Enter a number: 6 SIX

While loop — A statement is executed only once from top to bottom. — For example ‘if is a statement that is executed by Python interpreter only once. — But a loop is helpful to execute repeatedly. — For example for and while loops in python . They are useful to execute a group of statements repeatedly several times. — The while loop is useful to execute a group of statements several times depending on whether a condition is True or False. The syntax of while loop is : while condition: statements 57

While loop — Python interpreter first checks the condition. If the condition is True, then it will execute the statements written after colon(:) . — After executing the statements it will go back and check the condition again. — If the condition again found True, then it will again execute the statements. — In this way, as long as the condition is True, Python interpreter executes the statements again and again. — Once the condition found to be False, then it will come out of the while loop. 58

While loop 59

While loop — Python program to display numbers from 1 to 10: x=1 while x<=10: print(x) x+=1 print("End") 60 Output: ???

While loop What is output of the python program?? x=1 while x<=10: print(x) x+=1 print("End") 61 Output: ???

While loop — Write a Python program to display even numbers between 100 to 200. 62

While loop — Write a Python program to display even numbers between 100 to 200. x=100 while x>=100 and x<=200: print(x) x+=2 63 Output: ???

While loop — Write a Python program to display even numbers between m and n. 64

While loop — Write a Python program to display even numbers between m and n. m=int(input(“Enter the lower value of range:”)) n=int(input(“Enter the higher value of range:”)) x = m if x%2 != 0: x += 1 while x>=m and x<=n: print(x) x +=2 65 Output: Enter the lower value of range: 11 Enter the higher value of range: 20 12,14,16,18,20

66

range — A range() object or range() function in Python is useful to provide a sequence of numbers. — range(n) gives numbers from 0 to n-1. — The range can be represented in following ways: — range(10) : return numbers 0 to 9. — range(5,10) : starting number(5) and ending number(9). returns 5 to 9. — range(1,10,2) : alongwith starting and ending numbers, step size (increment) can also be mentioned.(step size = 1 when not mentioned) returns 1,3,5,7 and 9. 67

For loop — A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). — This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. — With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. — The syntax of for loop is : for var in sequence: statements — Important: Increment operator is not used in Python in case of For Loop like in C and Java. 68

For loop Write a Python program to display odd numbers between 1 and 10. for i in range(1,10,2): print(i) 1,3,5,7,9 — Write a Python program to display odd numbers between m and n. m=int(input(“Enter the starting range:”)) n=int(input(“Enter the end of the range:”)) x = m if x%2 != 1: x = x+1 for i in range(x,n,2): print(i) Enter the minimum and maximum value of range: 10,20 11,13,15,17,19 69

For loop A Python program to display characters of string using for loop: str = “Hello” for ch in str: print(ch) H e l l 70

The break statement The break statement can be used inside a for loop or while loop to come out of the loop. When “break” statement is executed, the Python interpreter jumps out of the loop to process the next statement in program. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops. 71

The break statement For example, a program to display numbers 1 to 10 using break statement in while loop. x=1 while x<=10: print(x) x+=1 if x==5: break print("Out of the loop") 72 Output: ??? 1 2 3 4 Out of the loop

The continue statement The continue statement is used in a loop to go back to the beginning of the loop. It means when continue is executed,the next repetition will start. When continue is executed ,the subsequent statements in the loop are not executed. “Continue” skips the the rest of the statements in the blocks and continue with next iteration of the loop[ 73

The continue statement Example For example, a program to display numbers 1 to 5 using continue statement in while loop for x upto 10. x=1 while x<=10: x+=1 if x==5: continue print(x) print(“Out of the loop”) 74 Output: ??? 2 3 4 6 7 8 9 10 Out of the loop

The Pass statement The pass statement does not do anything. It is used with ‘if statement’ or inside a loop to represent no operation. The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute 75

The Pass statement Example x=1 while x<=10: print(x) x+=1 if x==5: pass print(“Out of the loop”) 76 Output: ??? 2 3 4 5 6 7 8 9 10 11 Out of the loop

4. Comparison/ Relational Operators — Use to compare two quantities. — Always results in True/False depending on values compared. — Let us assume, x = 1 and y =2. 77 Operator Description Example Result == Equals operator. True if x and y are equal. x==y False != Not Equals operator. True if x and y are not equal. x!=y True > Greater than operator. True if x>y x>y False >= Greater than or equal operator. x>=y False < Less than operator. True if x<y x<y True <= Less than or equal operator. x>=y True

Functions A function is similar to a program that consists of a group of statements that are intended to perform a specific task. So, when there are several tasks to perform, programmer need to write several functions. Types of functions Built-in functions : Already included functions in IDLE. For example, print() function – to display output sqrt() function – to calculate square root values power() function – to calculate power value User-defined functions : A programmer can also create his own functions called as user defined functions.

Functions Advantages of the functions: Functions are important in programming because they are used to process data, make calculations or perform any other task. Once function is written it can be reused whenever required, so we will need not write same code again and again, so redundancy is reduced. Functions provides modularity for programs. Code maintenance will become easy because of functions. For example, when a new feature has to be added, a new function can be written and integrated. Similarly, existing function can be deleted whenever a particular feature is no longer useful. When there is an error in the software, the corresponding function can be modified without disturbing the other functions in software. The use of functions will reduce the length of a program.

Defining a Function The syntax for defining functions is: def function name (parameter1, parameter2, ….): “““ function docstring””” function statements We can define a function using the keyword def followed by function name. After it parameters should include in parentheses. After parentheses, put a semicolon (:) to represent the beginning of function body. The body consists of following parts: Function docstring: Docstring is nothing but a multiline comment to describe the use of function. It is optional. Function statements: It consists of the statements which constitutes the logic of function to perform the task. These statements should be written with proper indentations.

Defining a Function For example consider a following function: def sum ( a,b ): “““ This function finds sum of two numbers””” c = a + b print (c) Here, we define a function with sum as a function name, to add two variables a and b written inside parentheses after function name. These variables are called as ‘parameters’. A parameter is a variable that receives data from outside into a function. So, here this function can receive two values from outside and those values are stored in variables ‘a’ and ‘b’.

Defining a Function After parentheses, we put a colon (:) that represents the beginning of the function body. The function body contains group of statements called as “suite”. It started with docstring which is optional. After docstring, we have written the next steps which constitutes the logic of function. Here, we have to find the sum of two variables and then print the output, so, we have written as (with proper indentation), c = a + b print (c) The parameters ‘a’ and ‘b’ contain the values which are added and result is stored in ‘c’ and then displayed using print() function.

Calling a Function A function cannot run on its own, it runs only when we call it. While calling a function, parameter values should be passed in parentheses as shown: sum (10, 15) Here, sum function is called and two values 10 and 15 are passed. When this statement is executed, the Python interpreter jumps to the function definition and copies the values 10 and 15 into the parameters ‘a’ and ‘b’ respectively. These values are processed by function body & result is obtained. The values passed to a function are called as ‘arguments’ . So, 10 and 15 are arguments here.

Calling a Function A function once written, it can be used again and again, whenever required as shown in example below. def sum ( a,b ): c = a + b print(“Sum = ”,c) x = sum (10, 15) # called first time Sum = 25 y = sum (2.5, 8.25) Sum = 10.75 # called second time As shown above, function is called twice. Also, when it is called first time, we have passed integer values as arguments, whereas second time, float values as arguments. Means, as we didn’t define the datatype of arguments, during runtime, they are assume to be of any type. This is called as ‘dynamic typing.’

Returning Results from a Function Suppose, in previous example, we make a change such that it will not display the result. def sum (a,b): c = a + b # didn’t write print function x = sum (10, 15) print (x) None y = sum (2.5, 8.25) print (y) None It means, the output value (result) is not available outside the function. To solve this, we have to return the result from function.

Returning Results from a Function It is shown in following example. def sum (a,b): c = a + b return c # returns result x = sum (10, 15) print (x) # returned result is copied into x 25 y = sum (2.5, 8.25) print (y) # returned result is copied into y 10.75

Functions Write a Python program using function to display a factorial of a number entered from keyboard. def fact(n): prod = 1 for i in range (1, n+1): prod = prod * i return prod x = int (input ("Enter the number: ")) print("The factorial of {} is {}".format( x,fact (x))) Enter the number: 2 The factorial of 2 is 2 Enter the number: 3 The factorial of 3 is 6 Enter the number: 5 The factorial of 5 is 120

Functions Write a Python program using function to display a factorial of all numbers from 1 to entered number from keyboard. def fact(n): prod = 1 for i in range (1, n+1): prod = prod * i return prod x = int (input ("Enter the number: ")) for i in range (1, x+1): print("The factorial of {} is {}".format(i,fact(i)))

Functions The output is: Enter the number: 3 The factorial of 1 is 1 The factorial of 2 is 2 The factorial of 3 is 6 >>> Enter the number: 5 The factorial of 1 is 1 The factorial of 2 is 2 The factorial of 3 is 6 The factorial of 4 is 24 The factorial of 5 is 120 >>> Enter the number: 10 The factorial of 1 is 1 The factorial of 2 is 2 The factorial of 3 is 6 The factorial of 4 is 24 The factorial of 5 is 120 The factorial of 6 is 720 The factorial of 7 is 5040 The factorial of 8 is 40320 The factorial of 9 is 362880 The factorial of 10 is 3628800

Functions Write a Python program using function to display whether a number is prime or not. def prime(n): x = 1 for i in range (2, n): if n % i ==0: x = 0 break else: x = 1 return x num = int (input ("Enter the number: ")) result = prime( num ) if result == 0: print ( num , "is not a prime number: ") else: print ( num , "is a prime number: ")

Functions The output is: Enter the number: 2 2 is a prime number: Enter the number: 3 3 is a prime number: Enter the number: 4 4 is not a prime number: Enter the number: 5 5 is a prime number: Enter the number: 6 6 is not a prime number: Enter the number: 7 7 is a prime number:

Returning Multiple Values from a Function A function returns a single value in the programming languages like C and Java. But in Python, a function can return multiple values as: return a, b, c Here three values a, b, c are returned as a tuple. To copy these values, three variables should be used as, x, y, z = function () Here, variables x, y, z received three values returned by a function. Similarly, when several results are returned, we can retrieve them using for loop or while loop.

Returning Multiple Values from a Function Write a Python program to calculate the addition and subtraction of two variables using single function and return the results. def add_sub (a,b): c = a + b d = a – b return c, d x, y = add_sub (5, 10) print (“The addition is: ”, x) print (“The subtraction is: ”, y) The addition is: 15 The addition is: -5

Returning Multiple Values from a Function Write a Python program to calculate the addition, subtraction, multiplication and division of two variables using single function and return the results. def add_sub_mul_div ( a,b ): c = a + b d = a – b e = a * b f = a / b return c, d, e, f out = add_sub_mul_div (10, 5) print (“The results are: ”) for i in out: print (i, end = ‘ ’) The results are: 15 5 50 2.0

Functions are First Class Objects In Python, functions are considered as first class object, means we can use functions as perfect objects. In fact, when we create a function, Python interpreter internally creates an object. As functions considered as objects, following points are possible: It is possible to assign a function to a variable. It is possible to define one function inside another function. It is possible to pass a function as parameter to another function. To understand these points, consider next few simple programs.

Functions are First Class Objects A Python program to assign a function as a variable. def display ( str ): return ‘Hi’ + str x = display (“Krishna”) # function is assigned to variable x print (x) Hi Krishna A Python program to define a function inside a function. def display ( str ): def message (): # function is defined inside function return ‘How are you’ x = message () + str return x print (display(“Krishna”)) How are you Krishna

Functions are First Class Objects To pass message () function as argument to display () function. def display (fun): return ‘Hi’ + fun def message (): return “how are you” print (display (message()) # function as argument Hi Krishna ????

Formal and Actual Arguments When a function is defined, it may have some parameters. These parameters are useful to receive values from outside the function and called as ‘formal arguments’. When we call the function, we should pass the data or values to the function called as ‘actual arguments’. def sum ( a,b ): # a, b are formal arguments c = a + b print (“Sum = ”, c) x, y = 10, 20 sum (x, y) # x, y are actual arguments The actual arguments are used in function call are of 4 types: Positional Arguments Keyword Arguments Default Arguments Variable Length Arguments

Positional Arguments These are the arguments passed to a function in correct positional orders. Here, the number of arguments and their positions in function definition should match exactly with the number and positions of the arguments in the function call. For example, take a function definition with two arguments as, def attach (s1, s2): s3 = s1 + s2 This function expects two strings that too in that order only. Suppose we pass the two strings, then output will be, attach (‘New’, ‘York’) >>> NewYork attach (‘York’, ‘New’) >>> YorkNew If we call function by passing three values, then will display an error as, attach (‘New’, ‘York’, ‘City’)

Positional Arguments The same program can be written as, def attach (s1, s2): s3 = s1 + s2 print (s3) attach (‘New’, ‘York’) attach (‘York’, ‘New’) attach (‘New’, ‘York’, ‘City’) The output is: NewYork YorkNew Traceback (most recent call last): File "< stdin >", line 1, in <module> TypeError : attach() takes 2 positional arguments but 3 were given

Keyword Arguments Keyword arguments are arguments that identify the parameters by their names. For example, a definition of a function that displays concatenation of two strings as, def attach (s1, s2): At the time of calling, we can pass the arguments directly as, attach (s1 = 'New', s2 = 'York') Here, we mention keywords “s1” and “s2” and passed their values. As these are keywords, we can change their positions also. attach (s2 = 'York', s1 = 'New') In this way, even we can change the order of arguments, there will not be any problem as parameter names will guide where to store that value.

Keyword Arguments The same program can be written as, def attach (s1, s2): s3 = s1 + s2 print (s3) attach (s1 = 'New', s2 = 'York') attach (s2 = 'York', s1 = 'New’) The output is: NewYork NewYork

Default Arguments We can also mention some default value for function parameters in function definition. For example, def attach (s1, s2 = 'York’): Here, the first argument is ‘s1’ whose default value is not mentioned, but the second argument is ‘ s2’ whose default value is mentioned as ‘York’. If we mention the value of ‘s2’ , then mentioned value is taken. And if we do not pass ‘s2’ value, then default value ‘York’ is taken. So, default argument is an argument that assumes a default value if a value is not provided in the function.

Default Arguments Consider next program, def attach (s1, s2 = 'York'): s3 = s1 + s2 print (s3) attach (s1 = 'New', s2 = Delhi') attach (s1 = 'New’) # need not to mention default argument in function call. The output is: NewDelhi NewYork

Variable Length Arguments Sometimes, the programmer does not know how many values a function may receive. In that case, the programmer cannot decide how many arguments to be given in the function definition. For example, the add function to add two numbers discussed earlier: def add (a,b): But, the user who is using this function may want to use this function to add three numbers. In this case there is a chance that user may provide three arguments to add function as, add (5, 10, 15) Here, the add() function will fail and error will displayed .

Variable Length Arguments If the programmer wants to develop a function that can accept a ‘n’ arguments, that is also available in Python. For this purpose a ‘variable length argument’ is used in function definition, which is an argument that can accept any number of values. A variable length argument is written with asterisk symbol (*) before it in the function definition as, def add (farg, *args): Here, ‘farg’ is a formal argument and ‘args’ represents variable length argument. We can pass one or more arguments to this ‘args’ and it will store them all in a tuple.

Variable Length Arguments A Python program to add ‘n’ numbers. def add ( farg , * args ): print("Formal argument = ", farg ) sum = 0 for i in args : sum += i print ("The sum of all arguments = ", farg + sum)

Variable Length Arguments The output is: >>> add (5, 10) Formal arguments = 5 The sum of all arguments = 15 >>> add (5, 10, 15) Formal arguments = 5 The sum of all arguments = 30 >>> add (5, 10, 15, 20) Formal arguments = 5 The sum of all arguments = 50

Local and Global Variables Local Variable: When we declare a variable inside a function, it becomes a local variable. A variable is a local variable whose scope is limited only to that function where it is created and not outside the function. Consider a following example, def myfunction (): a = 1 a += 1 print (a) myfunction () >>> 2 print (a) >>> NameError : name 'a' is not defined Here, ‘a’ is declared inside a myfunction () and hence is available inside that function. When it called outside function, it raises an error with a message, as shown in output.

Local and Global Variables Global Variable: When a variable is declared above a function, it becomes global variable. Such variables are available to all functions which are written after it. Consider following example, a = 1 def myfunction (): b = 2 print (‘a = ’, a) print (‘b = ’, b) myfunction () >>> a = 1 b = 2 print (a) >>> 1 print (b) >>> NameError: name ‘b' is not defined

Global Keyword Sometimes , the global variable and the local variable may have the same name. In that case function, by default, refers to the local variable and ignores the global variable. For example, a = 1 def myfunction (): a = 2 print (‘a = ’, a) # display local value myfunction () >>> a = 2 print (‘a = ’, a) >>> a = 1 # display global value Here, inside a function, local value of a is referred, whereas outside the function, global value is referred.

Global Keyword When a programmer wants to modify the global variable used inside a function, a ‘global keyword’ can be used before variable at the beginning of program as shown below, a = 1 def myfunction (): global a print ('global value of a = ', a) a = 2 print ('modified global value of a = ', a) print ('a = ', a) myfunction () print ('a = ', a) a = 1 global value of a = 1 modified global value of a = 2 a = 2

Recursive Functions A function that calls itself is known as a ‘Recursive Function’. For example, the factorial of 3 can be written as, factorial (3) = 3 * factorial (2) Here, factorial (2) = 2 * factorial (1) factorial (1) = 1 * factorial (0) Now, if we know that the factorial (0) = 1, then all the preceding statements will be evaluated and give the result as, factorial (3) = 3 * factorial (2) = 3 * 2 * factorial (1) = 3 * 2 * 1 * factorial (0) = 3 * 2 * 1 * 1 = 6 From above example, we can write as, factorial (n) = n * factorial (n-1)

Recursive Functions So, in this process, a factorial () function to calculate a factorial of ‘n’ value will call itself to calculate factorial of ‘n – 1’ value. So, we can implement factorial () function using recursion as below, result = 0 def factorial (n): if n == 0: result = 1 else: result = n * factorial (n-1) return result x = int(input("Enter the number to find factorial: ")) y=factorial (x)) print("The factorial is ”, y )

The output is: Enter the number to find factorial: 10 Factorial of 10 is 3628800 Recursive Functions

Anonymous Functions (Lambdas) A function without a name is calle d ‘Anonymous Function’ . So far, functions we wrote were defined using a keyword ‘ def ’ . They are defined using a keyword ‘lambda’ , hence they are called as Lambda functions. For example, a function to calculate square: def square (): return x*x The same can be written using anonymous function as, lambda x: x*x As shown, for anonymous function first keyword ‘lambda’ is written, followed by an argument of the function i. e. ‘x’ here. Then colon (:) represents the beginning of functio n that contains an expression x*x .

Anonymous Functions (Lambdas) Observe that, any name is not used for a function here. So, the format of lambda function is: lambda argument_list: expression Normally, if a function returns some value, it is assigned to a variable as, y = square (5) But, lambda function return a function and hence they should be assigned to a function as, f = lambda x: x*x Here, ‘f’ is the function name to which the lambda expression is assigned. We can call an assigned function as, value = f(5)

A Python program to create a lambda function that returns a square value of a given number. f = lambda x: x*x y = f(5) print ("The square of 5 is: ", y) The square of 5 is: 25 x = int (input("Enter a number whose square to be find: ")) f = lambda x: x*x y = f(x) print ("The square of {} is: {}".format (x,y)) Enter a number whose square to be find: 10 The square of 10 is: 100 Anonymous Functions (Lambdas)

Same example: x = int (input("Enter a number whose square to be find: ")) f = lambda x: x*x y = f(x) print (“ The Square of number is : ”, y) Enter a number whose square to be find: 10 The Square of number is : ”, 100 Anonymous Functions (Lambdas)

IMP: Lambda functions contain only one expression and they return the result implicitly. Hence, ‘return’ statement is not written in the lambda functions. A Python program to find bigger number in two given numbers: fun = lambda x,y: max(x,y) x,y = [int(n) for n in input("Enter two numbers separated by space: ").split(,)] print ("The bigger number in {} and {} is: {}".format (x,y,fun(x,y)) Enter two numbers separated by space: 12 56 The bigger number in 12 and 56 is: 56 Anonymous Functions (Lambdas)

A Python program to find sum of two variables: f = lambda x,y: x+y y = f(5,10) print ("The sum of 5 and 10 is: ",y) The sum of 5 and 10 is: 15 Because a lambda function is always represented by a function, we can pass a lambda function to another function. Means, we can pass a function (lambda) to another function, which makes it easy to process the data. For example, lambda functions are generally used with functions like filter(), map() or reduce(). Anonymous Functions (Lambdas)

A filter function is useful to filter out the elements of a sequence depending on the result of a function. A sequence is supplied to a filter function as, filter (function, sequence) Here, ‘function’ represents a function name that returns either True or False, and ‘sequence’ represents a list, string or tuple. The ‘function’ is applied to every element of the ‘sequence’ and when the function returns True, the element is extracted otherwise it is ignored. For example, to filter out even numbers from a sequence (list) which returns only those elements which are even. Using Lambdas with filter() Function

A Python program using filter() to filter out even numbers from a list. def is_even (x): if x%2 == 0: return True else: return False lst = [8, 10, 15, 18, 23, 26, 28, 35, 37, 40] lst1 = list(filter(is_even, lst)) print (lst1) [8, 10, 18, 26, 28, 40] Using Lambdas with filter() Function

But, passing lambda function to filter function is more elegant. Now, we will rewrite the previous program using lambda function as, lst = [8, 10, 15, 18, 23, 26, 28, 35, 37, 40] lst1 = list(filter(lambda x: (x % 2 == 0), lst)) print (lst1) [8, 10, 18, 26, 28, 40] As shown, in previous program first we have to write a function first and then call in filter function. But in later, as shown complete function writing is not done and hence, reduced the complexity of a program using lambda function. Using Lambdas with filter() Function

The map() function is similar to filter() function, but it acts on each element of the sequence and perhaps changes the element. The format for map() function is same as that of filter() i.e., map (function, sequence) The ‘function’ performs a specified operation on all the elements of the ‘sequence’ and modified elements are returned in another sequence. For example, consider a function that to find the squares of all the elements in a list and copies them in a new list using map() function. Using Lambdas with map() Function

A Python program using map() to find the squares of all the elements from a list. def square (x): return x*x lst = [1, 2, 3, 4, 5] lst1 = list(map(square, lst) print (lst) print (lst1) [1, 2, 3, 4, 5] [1, 4, 9, 16, 25] Using Lambdas with map() Function

But, passing lambda function to map function is more elegant. Now, we will rewrite the previous program using lambda function as, lst = [1, 2, 3, 4, 5] lst1 = list(map(lambda x: x*x, lst)) print (lst1) [1, 4, 9, 16, 25] It is also possible to use map() function on more than one list (or sequences) if the lists (or sequences) are of same length. In this case, map() function takes the lists as arguments of the lambda function and performs the operation. Using Lambdas with map() Function

For example, map(lambda x,y : x*y :, lst1, lst2) Here, lambda function has two arguments ‘x’ and ‘y’ . Hence, ‘x’ represents ‘lst1’ and ‘y’ represents ‘lst2’ . Since, lambda is showing ‘x*y’ , the respective elements from lst1 and lst2 and product is returned. Now, we will write the said program using lambda function as, lst1 = [1, 2, 3, 4, 5] lst2 = [10, 20, 30, 40, 50] lst3 = list(map(lambda x,y : x*y, lst1, lst2)) print (lst3) [10, 40, 90, 160, 250] Using Lambdas with map() Function

The reduce function reduces a sequence of elements to a single value by processing the elements according to a function supplied. The format for reduce() function again is, reduce (function, sequence) Here, reduce() function reduces the list to a final value as indicated by the lambda function. Consider, to find the product of all the elements in a list. Here, a lambda function taking two arguments (consecutive elements from list) and returning their product. Means, starting from 0 th element, product of 0 th and first element is multiplied by 2 nd element and so on. Using Lambdas with reduce() Function

Process is repeated to return a single value as a result as shown. lst = [1, 2, 3, 4, 5] 1 * 2 = 2 lst = [2, 3, 4, 5] 2 * 3 = 6 lst = [6, 4, 5] 6 * 4 = 24 lst = [24, 5] 24 * 5 = 120 lst = [120] Now, we will write the said program using lambda function as, from functools import * lst = [1, 2, 3, 4, 5, 6] result = reduce (lambda x,y : x*y, lst) print (result) 120 Using Lambdas with reduce() Function

Actually reduce() is not a library function in Python. Since, it belongs to ‘functools’ module in Python, import it from that module using statement. from functools import * Another example to calculate sum of numbers from 1 to 50 using reduce function with lambda function from functools import * result = reduce (lambda x,y : x+y, range(1,51)) print (result) 1275 Using Lambdas with reduce() Function

The built-in functions we have used, such as abs, pow , and max, have produced results. Calling each of these functions generates a value, which we usually assign to a variable or use as part of an expression. biggest = max(3, 7, 2, 5) a = pow (5,4) But so far, none of the functions we have written has returned a value. In this chapter, we are going to write functions that return values, which we will call fruitful functions, for want of a better name. The first example is area, which returns the area of a circle with the given radius. Fruitful Functions

It can be written using a function as, def area(radius): temp = 3.14159 * radius**2 return temp print (area (5)) 78.53975 We have seen the return statement before, but in a fruitful function the return statement includes a return value. This statement means: Return immediately from this function and use the following expression as a return value. Fruitful Functions

The expression provided can be arbitrarily complicated, so we could have written this function more concisely as, def area(radius): return 3.14159 * radius**2 print (area (5)) 78.53975 On the other hand, temporary variables like temp often make debugging easier. Sometimes it is useful to have multiple return statements, one in each branch of a conditional. Fruitful Functions

For example, built-in ‘abs’ function to calculate the absolute value of a variable can be used in a program as, def absolute_value (x): if x < 0: return -x else: return x print (absolute_value (5)) >>> 5 print (absolute_value (-8)) >>> 8 print (absolute_value (0)) >>> 0 Fruitful Functions

Since these return statements are in an alternative conditional, only one will be executed. As soon as one is executed, the function terminates without executing any subsequent statements. Code that appears after a return statement, or any other place the flow of execution can never reach, is called ‘dead code’ as it does not executed. In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement. Fruitful Functions

The following version of absolute_value fails to do this: def absolute_value(x): if x < 0: return -x elif x > 0: return x print (absolute_value (5)) >>> 5 print (absolute_value (-8)) >>> 8 print (absolute_value (0)) >>> None This version is not correct because if x happens to be 0, neither condition is true, and the function ends without hitting a return statement. Fruitful Functions

In this case, the return value is a special value called ‘None’, which is not an absolute value of 0. None is the unique value of a type called the NoneType. All Python functions return None whenever they do not return another value. So, here a defined absolute_value function is not a fruitful function as it does not yield output every time. Fruitful Functions
Tags