Python Programming for problem solving.pptx

NishaM41 70 views 173 slides Aug 12, 2024
Slide 1
Slide 1 of 173
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
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173

About This Presentation

Python Programming for problem solving


Slide Content

Mrs. M. Nisha Assistant Professor Department of CSE Akshaya College of Engineering and Technology Python for Everyone

a general purpose, interpreted, high- level programming Python is language. It was created by Guido Van Rossum in1991 . It was designed with code readability and its syntax allows the programmers to express the code with fewer lines of code. Python programming relies on indentation using white space , to define the scope of loops and functions. Introduction

Introduction Python is a popular programming language for several reasons: Readability and Simplicity : Python's syntax is clear and easy to understand 2. Versatility : Used in various fields, including web development, data analysis, machine learning, artificial intelligence, scientific computing, and automation. 3.Extensive Libraries and Frameworks : Django and Flask for web development, NumPy and pandas for data analysis, TensorFlow and PyTorch for ML, and many more. 4.Community Support : This means extensive documentation, and numerous forums 5. Cross-Platform Compatibility : It can run on various operating systems, such as Windows, macOS , and Linux, without requiring significant changes to the code. 6.Integration Capabilities : Python can easily integrate with other languages and technologies 7.Rapid Development : Python allows for rapid development and prototyping due to its high-level nature and the availability of extensive libraries. 8.Popularity in Data Science and AI : Python is the go-to language for data science, ML, and AI due to its powerful libraries and frameworks that simplify complex tasks.

Python Features

Applications of Python

Python Environmental Setup Step 1: Download Python Installer https://www.python.org/downloads/

Python Environmental Setup Step 2: Run the Executable Installer

Python Interpreter Mode s Python Interpreter Python is an interpreted object- oriented programming language. Interpreter is a translator, which translates the given code line- by- line into machine readable bytecodes. If any error occurs, it stops the translation until the error is fixed. Compiler is a translator, which translates the entire code as whole into machine readable bytecode and displays all the error during compilation.

Python Interpreter Mode s Python Interpreter Modes Python Interpreter consists of two modes, Interactive mode Script mode Both are the two primary ways to run the Python code. Both modes play essential roles in Python development

Python Inter active Mode Python Interactive Mode Python Interactive mode is used for executing single line or single block of code, which provides immediate feedback for each statement. Advantages It is convenient for writing short lines of code. It helps the beginners to understand the execution of the code.

Python Interactive Mode Python Interactive Mode : Example

Python Script Mode Python Script Mode Python script mode is used for executing multiple blocks of code. Script files are stored using the extension “ .py” Advantages It helps to provide proper and organization for complex projects. Code reusability

Python Script Mode Python Script Mode : Example

Comments Python comments are the non- executable piece of code that are igorned by the interpreter at the time of program execution. In python, comments are represented with the symbol “#”. Comments enhance the readability of code, that helps the programmers to understand the meaning of the code. Types of Comments Single-line comments Multi- line comments

Comments Single- line Comments Single-line comments starts with the hashtag symbol “#” with no white space. If a comment extends to next line, then put a hashtag symbol to the next line.

Comments Multi- line Comments Python does not really support multi-line comments. To include it, we can either use “#’ for each line or multi-line string in the code.

Identifiers and Keywords Identifiers:- Identifiers are the user-defined name given to a variables, functions, methods. It can start with an alphabets (A to Z) or underscore. It is always good to provide meaningful name to the identifiers for better understanding about the code. Rules for Naming Identifiers:- Identifiers cannot be a reserved python keywords. They are case sensitive. (Eg:- Uppercase & Lowercase identifiers are distinct) Identifiers contain digits (0 to 9) but should not start with digit.

Identifiers and Keywords Rules for Naming Identifiers:- Identifiers does not allow punctuations like %, $, @, etc. It does not contain any other special characters other than underscore(_). If identifier starts with _ symbol, then it indicates that it is private . If identifier starts with (two under score symbols) indicating that strongly private identifier . If an identifier starts and ends with two underscore symbols then it is called as magic methods .

Identifiers and Keywords Examples for Valid Identifiers:- ab10c, abc_DE, _, _abc, _1_var, abc Examples for Invalid Identifiers:- 123total, 12Name, name$, total- mark, continue, var#1, !var1

Identifiers and Keywords Keywords:- Python Keywords are the pre- defined and reserved words which have a special meaning. Keywords cannot be used as identifiers and function name. It is case sensitive. In python there is an inbuilt keyword module, which provides kwlist attribute to display the list of python keywords.

Identifiers and Keywords Examples for Keywords:-

Identifiers and Keywords Examples for Keywords:-

Data Types Python data type is used to identify the type of data.

Data Types Numeric Data Type:- Numeric data type represents the numeric values such as integer, float and complex data. Integer:- Integer can be positive or negative whole number without any fractions or decimals. Eg:- 10, 1000, - 23

Data Types Int eger valu e s c an be r epr ese nte d in fo llow in g w ays D eci m al f orm (B ase 10) - to 9 B inar y f orm (B as e 2) - 0, 1, lite ral s pr efix st arts wi th 0B o r 0b O ctal fo rm (Bas e 8) - t o 7, lit eral s p ref ix s tart s w ith 0o or 0O H exadecim al (Bas e 16) - 0 to 9, A to F, lite ral s pr efix st arts wi th 0X or 0x Numeric Data Type:- Integer:- Eg:-

Data Types Fl oat val ues ar e re pre sen ted by a d eci mal po int val ue . - Eg: - 2. 5, - 28. 98 , et c The flo ati ng poi nt val u es can als o r epr esen ted by a exp one nti al f orm . - E g:- 1.2e3, etc Numeric Data Type:- Float:- Eg:-

Data Types A complex num be r is rep res ent ed by a co mp lex clas s. It is s peci fied as (r eal par t) + (im agi nar y par t)j. For exampl e :- – 2+ 3j Numeric Data Type:- Complex Number:- Eg:

Data Types Boolean Data Type:- Boolean data type is represented by the boolean values. Boolean values are represented by True (1), False (0) Eg:-

Data Types Sequence Data Type:- Sequence data type is the ordered collection of similar or different data types. In Python, the sequence data types are as follows, String List Tuple String:- String is a sequence of characters enclosed within single quotes, double quotes or triple quotes. Eg:- ‘Hello’, “Hello World”, '''hai''', """hiiii"""

Data Types Examples of String Representation:-

Data Types Examples of String Memory Allocation:-

Data Types Examples of String Indexing:-

Data Types Slicing of String:- String slicing is a piece of string obtained from the sequence of string. Slicing have been performed using the operator “[ : ]”.

Data Types Sequence:- List:- List is a mutable & ordered collection of elements of heterogeneous data type. In list, the elements are separated by commas and that are enclosed within square bracket “[ ]” Eg:

Data Types Example for List Indexing:- In list, the elements are represented with the index value from to n- 1. Eg:

Data Types Example for List Mutablility:- Eg:

Data Types : Sequence Tuple:- Tuple is immutable & ordered collection of elements of heterogeneous / homogeneous data type. The elements are separated by commas and that are enclosed within square bracket “( )” Eg:

Data Types : Sequence Example for Tuple Representation:-

Data Types Example for Tuple Indexing:- In tuple, the elements are represented with the index value from to n- 1. Eg:

Data Types Example for Tuple Immutablility:- Eg:

Data Types Set:- Set is an unordered, unindexed & unchangeable collection of elements. Eg:-

Data Types Set:- Set is an unordered, unindexed & unchangeable collection of elements. Eg:-

Data Types Dictionary:- Dictionary is an ordered collection of elements enclosed within “{ }”. The elements in the dictionaries are mutable. Elements are represented by key : value pair Eg:-

Data Types Example for Dictionary Mutablility:- Eg:

Variables in Python Python Variable is a container that store values. The value can be immediately assigned to a variable in Python A Python variable is a name given to a memory location. It is the basic unit of storage in a program. Example Var = “Sri Eshwar" print(Var) 1

Rules for declaring Variables in Python A Python variable name must start with a letter or the underscore character. A Python variable name cannot start with a number. A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). Variable in Python names are case-sensitive (name, Name, and NAME are three different variables). The reserved words(keywords) in Python cannot be used to name the variable in Python. 2

Assigning a variable in Python Assigning an integer age = 45 Assigning a floating point salary = 1456.8 Assigning a string name = "John" print(age) print(salary) print(name) 3

Expression in Python An expression is a combination of operators and operands that is interpreted to produce some other value. An expression is evaluated as per the precedence of its operators. The expression types are Constant Expressions Arithmetic Expressions Integral Expressions Floating Expressions Relational Expressions Logical Expressions Bitwise Expressions 4

Constant Expression Constant expressions are expressions having constant values only. Constant Expression x = 15 + 1.3 print(x) Output 16.3 5

Arithmetic Expression An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis .The arithmetic operators are 6

Arithmetic Expression- Example Program x = 40 y = 12 add = x + y sub = x - y pro = x * y div = x / y print(add) print(sub) print(pro) print(div) Output 52 28 480 3.3333333333333335 7

Integral Expressions These are the kind of expressions that produce only integer results after all computations and type conversions. Program a = 13 b = 12.0 c = a + int(b) print(c) Output 25 8

Floating Expressions These are the kind of expressions which produce floating point numbers as result after all computations and type conversions. Example: # Floating Expressions a = 13 b = 5 c = a / b print(c) Output 2.6 9

Relational Expressions 10 In these types of expressions, arithmetic expressions are written on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per relational operator and produce a boolean output in the end. Example: # Relational Expressions a = 21 b = 13 c = 40 d = 37 p = (a + b) >= (c - d) print(p) Output True

Logical Expressions These are kinds of expressions that result in either True or False. It basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9 and will return False. 11

Logical Expressions- Example Example P = (10 == 9) Q = (7 > 5) # Logical Expressions R = P and Q S = P or Q T = not P print(R) print(S) print(T) 12 Output False True True

Bitwise Expressions- Example These are the kind of expressions in which computations are performed at bit level. Example a = 12 x = a >> 2 y = a << 1 print(x, y) Output 3 24 13

Operators Operator is a symbol that performs certain operations . Python provides the following set of operators Arithmetic Operators Relational Operators or Comparison Operators Logical operators Bitwise operators Assignment operators Special operators 1

1.Arithmetic Operators 2

1.Arithmetic Operators 3

1.Arithmetic operators 4

2.Relational operators 5

2.Relational operators 6

3.Equality operators 7

3.Equality operators 8

4.Logical operators 9

4.Logical operators 10

4.Logical operators 11

5. Bit- wise operators 12

5.Bitwise operators 13

5.Bitwise operators 14

6.Shift operators 15

6.Shift operators 16

7.Assignment operators 17

7.Assignment operators 18

7.Assignment operators 19

8.Ternary operators 20

8.Ternary operators 21

Special operators Identity Operators We can use identity operators for address comparison . 2 identity operators are available is is not r1 is r2 returns True if both r1 and r2 are pointing to the same object r1 is not r2 returns True if both r1 and r2 are not pointing to the same object Python defines the following 2 special operators Identity Operators Membership operators 22

Special operators - Example 23

2.Membership operators We can use Membership operators to check whether the given object present in the given collection .(It may be String, List,Set,Tuple or Dict) In - >Returns True if the given object present in the specified Collection not in - > Returns True if the given object not present in the specified Collection 24

Operators Precedence 25 . If multiple operators present then which operator will be evaluated first is decided by operator precedence. The acronym PEMDAS ( Parentheses, Exponentiation, Multiplication ,Division, Addition, Subtraction) is a useful way to remember the rules:

Operators Precedence - Example 26 .

1 Control Flow Statements Control Flow Statements Sequential Statements Branching Statements Conditional Statements In a program, the control flow is the order in which the program’s code executes. Control statements are elements in the source code that control the flow of program execution . The control flow of a Python program is regulated by sequential statements, conditional statements, loops, and function calls . if if- else Nested if If-elif- else Un Conditional Statements break continue pass Loop Statements for while

Example 1 : Greet a user with the Welcome Message “ Welcome<<user name>> ” IPO Chart:- Sequence Program:- Username=input(“Enter your name”) print(“Welcome”, Username) Input Processing Output Read username Algorithm Step 1 : Start Step 2 : Input username Step 3 : Print Welcome username Step 4 : Stop “Welcome username” Output:- XYZ Welcome XYZ 2

Conditional Statements also known as selection statements , are used to make decisions based on a given condition . If the condition evaluates to True , a set of statements is executed, otherwise another set of statements is executed. Conditional Statements 3

Types of Conditional Statements:- Conditional Statement (if statement) Alternative Statement (if- else statement) Chained Conditional Statement (if-elif- else statement) Nested If Statement Conditional Statements : Types 4

Conditional Statements are also known as If Statement , which executes only if the condition given in the if statement is True . If the condition is False, then the If statement is not executed. Syntax:- 5 If Statement if condition: Statement

Example 1: Python program to determine whether a person is eligible to vote. IPO Chart:- Program age=int(input(“Enter a number”)) if age>=18: print(“You are Eligible to vote”) Conditional Statement : If Statement Input Processing Output Prompt the user to enter a person age Step 1: Start Step 2: Read the value of age Step 3: Check the condition age is greater than or equal to 18. If True, goto Step 3.1 Step 3.1: Print “You are eligible” Step 4: Stop You are eligible Output You are Eligible to Vote 6

Alternative Statements are also known as If–Else Statement , in which the “ If Statement ” executes the statements only if the condition is True . If the condition is False, then the Else statement gets executed. If- Else Statement Syntax if condition: Statements else: Statements 7

Example 1 : To check whether the given number is odd or even number IPO Chart: If- Else Statement Program: ( Even_odd.py ) number = int(input("Enter a number:\n")) if (number % 2) == 0: print(number," is Even number") else: print(number," is Odd number") Input Processing Output number Example: number=10 Read number Check condition number %2==0, if condition true, print number is even Else print number is odd Print number is odd or even Example: 10%2==0 (True) 10 is even number 8

Example 1 : To check whether the given number is odd or even number Program: number = int(input("Enter a number:\n")) if (number % 2) == 0: print(number," is Even number") else: print(number," is Odd number") Trace Table: 9 If- else Statement Line No number number %2==0 Output 1 10 2 True 3 10 is Even number 4 5 - -

Chained conditional Statements are also known as if–elif- else Statement , in which the “i f Statement ” executes the statements only if the condition is True . “ elif Statement ” provides an alternative possibility for the “i f Statement ”. The execution of “Elif Statement” is same as the “if Statement” (i.e) “ elif Statement ” executes the statements only if the condition is True . If the condition given in the “ elif Statement ” is also False , then “ else Statement ” gets executed. If – elif - else Statement 10

Syntax if condition: Statements elif condition: Statements else: Statements If – Elif - Else Statement 11

Example 1 : To test whether a number entered by the user is negative / positive / zero. IPO Chart: If – Elif - Else Statement Program: ( pos_neg_zero.py ) num=int(input("Enter any number:\n")) if num > 0: print(num,"is Positive number") elif num == 0: print(num,"is Zero") else: print(num,"is Negative number") Input Processing Output number Example: a=- 7 Read number if number>0 then print “number is Positive” elif number<0 then print “number is Negative” else print “number is Zero” Print number is negative / positive / zero. Example: - 7 is Negative Number 12

Selection : If – elif - else Statement 13 Program: num=int(input("Enter any number:\n")) if num > 0: print(num,"is Positive number") elif num == 0: print(num,"is Zero") else: print(num,"is Negative number") Trace Table: Line No num num>0 num==0 else Output 1 - 7 2 False 3 - 4 False 5 - 6 True 7 - 7 is Negative Number

It means you can use one if or else if statement inside another if or else if statement(s). It is always legal to nest if-else statements. Nested If Statement 14

Example 1 : To find the greatest among three numbers. IPO Chart: Nested If Statement Input Processing Output 3 numbers Example: a=10, b=15, c=35 Read 3 numbers as a, b and c if a>b then if a>c then print a is largest else print c is largest elif b>c then print b is largest else print c is largest Print largest number Example: c is largest 15

Nested If Statement Example 1 : To find the greatest among three numbers Program: a=int(input("Enter the first number: ")) b=int(input("Enter the second number: ")) c=int(input("Enter the third number: ")) if a>b: if a>c: print(a,"is the greatest number than",b,"and",c) else: print(c,"is the greatest number than",a,"and",b) elif b>c: print(b,"is the greatest number than",a,"and",c) else: print(c,"is the greatest number than",a,"and",b) 16

17 Nested If Statement Example 1 : To find the greatest among three numbers Trace Table: Line No a b c a>b a>c b>c Output 1 12 2 13 3 10 4 False 5 6 7 8 9 True 10 13 is the greatest number than 12 and 10 11 12

Practice Exercises : Conditionals Write a program to check leap year or not. Write a program to display “Hello” if a number entered by the user is multiple of 5 otherwise print “Bye”. Write a program to accept number from 1 to 7 and display the name of day like 1 for Sunday, 2 for Monday and so on. Write a Python program to accept the cost price of a bike and display the road tax to be paid according to the following criteria. 18

Looping Statement is a process of executing the set of statements repeatedly until the condition is True. It is also known as looping statements or repetition. Iteration (Looping) Example : To repeat our daily routine as a student Looping Statements 19

While loop statement is a set of statements that are repeatedly executed only if the condition is True . When the condition becomes False, the loop gets terminated. While loop statement is also known as Entry- Controlled loop . Syntax:- while condition: statement Iteration : While Loop Statement 20

Example 1 : Print first N natural numbers. IPO Chart: 21 Iteration : While Loop Statement Input Processing Output N Value Example: N=3 READ N value INITIALIZE i as 1 WHILE i<=N PRINT i i=i+1 END WHILE Print N Natural numbers Example: N=3 The first 3 Natural Numbers are: 1, 2, 3 Program: N=int(input('Enter the value of N: ')) i=1 # initialization while i<=N: # Condition print(i) i=i+1 # Increment

22 Iteration : While Loop Statement Example 1 : Print first N natural numbers Trace Table Line No N i i<=N Output 1 3 2 1 3 True 4 1 2 2 3 True 4 2 2 3 3 True 4 3 2 4 3 False

For loop statement is a set of statements that are repeatedly or iteratively executed over a sequence. When becomes False , then the loop gets terminated. Syntax:- the condition Iteration : For Loop Statement Syntax for variable in sequence: statement 23

Example 1 : Calculate the factorial of a given number Note: In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n. Example: 5!= 5*4*3*2*1=120. IPO Chart: Iteration : For Loop Statement Input Processing Output N Value Example: N=5 READ N SET fact=1 IF n==0 THEN PRINT fact ELSE FOR i ← 1 to n COMPUTE fact=fact*i ENDFOR PRINT fact ENDIF Print factorial of N Example: N=5 The factorial of 5 is 120 24

Iteration : For Loop Statement Example 1 : Calculate the factorial of a given number Program: N = int(input("Enter a number: ")) # To take input from the user factorial = 1 if N < 0: # check if the number is negative, positive or zero print("Sorry, factorial does not exist for negative numbers") elif N == 0: print("The factorial of is 1") else: for i in range(1,N + 1): factorial = factorial*i print("The factorial of",N,"is",factorial) 25

Iteration : For Loop Statement Line No N factorial N<0 N==0 i range(1,N + 1) Output 1 5 2 1 3 False 5 False 8 1 True 9 1 8 2 True 9 2 8 3 True 9 6 Example 1 : Calculate the factorial of a given number Trace Table 26

Iteration : For Loop Statement Line No N factorial N<0 N==0 i range(1,N + 1) Output 8 4 True 9 24 8 5 True 9 120 8 6 False 10 120 Example 1 : Calculate the factorial of a given number Trace Table 27

It is used to transfers the control from one part of the program to another without any condition . Python supports three types of unconditional control statements: break continue pass Unconditional Control Statements 28

It is used to transfers the control from one part of the program to another without any condition . Python supports three types of unconditional control statements: break continue pass Unconditional Control Statements 29

Break statement is used to terminate the execution of the nearest enclosing loop in which it appears. When compiler encounters a break statement, the control passes to the statement immediately after the body of the loop. Syntax:- break Unconditional Statement : Break 30

Unconditional Control Statement : Break Example 1 : To print the numbers from 1 to 10. If the number is 3 then stop the process. IPO Chart: Input Processing Output Range of numbers Example: Range: 1 to 10 INITIALIZE i=1 WHILE i<=10 PRINT i IF i==3 THEN break i=i+1 PRINT “Done” Print numbers from 1 to 10 Example: 1 2 3 Done 31

32 Unconditional Control Statement : Break Program: i=1 while i<=10: print(i) if i==3: break i=i+1 print(“Done”) Example 1 : To print the numbers from 1 to 10. If the number is 3 then stop the process. Line No i i<10 Output i==5 1 1 2 True 3 1 4 False 6 2 2 True 3 2 4 False 6 3 2 True 3 3 4 True 7 Done Trace Table

Unconditional Control Statement : Break Example 2 : To get N inputs from the user and calculate the sum of the same. If user enters -1 then stop adding. IPO Chart: Input Processing Output N value N integer value from user Example: N: 5 User input 5 4 3 8 9 READ N value INITIALIZE i as 1, sum as WHILE i<=N READ num IF num==- 1 THEN break ELSE sum=sum+num END IF i=i+1 END WHILE PRINT sum Print sum of N inputs Example: N: 5 User Input 5 4 3 8 9 Sum of input value is: 29 33

Unconditional Control Statement : Break Example 2 : To get N inputs from the user and calculate the sum of the same. If user enters -1 then stop adding. Program: N=int(input("Enter the value of N")) i=1 sum=0 while i<=N: num=int(input("Enter the user inputs")) if num==- 1: break else: sum=sum+num i=i+1 print('The sum of user input is: ',sum) 34

35 Unconditional Control Statement : Break Example 2 : To get N inputs from the user and calculate the sum of the same. If user enters -1 then stop adding. Trace Table Line No N i sum i<=N num num==- 1 Output 1 5 2 1 3 4 True 5 5 6 False 7 5 8 2 4 True 5 8 6 False 7 13

Unconditional Control Statement : Break Example 2 : To get N inputs from the user and calculate the sum of the same. If user enters -1 then stop adding. Trace Table Line No N i sum i<=N num num==- 1 Output 8 3 4 True 5 7 6 False 7 20 8 4 4 True 5 - 1 6 True 11 20 36

Continue statement can only appear in the body of a loop. When compiler encounters a continue statement, then the rest of the statements in the loop are skipped and the control is unconditionally transferred to the loop. Syntax:- continue Unconditional Statement : Continue 37

Unconditional Control Statements: continue Example 1 : To get N inputs from the user and skip if user inputs negative number else calculate the sum of the user inputs IPO Chart: Input Processing Output N value N integer value from user Example: N: 5 User input 5 4 - 3 8 - 9 READ N value INITIALIZE i as 1, sum as WHILE i<=N READ num i=i+1 IF num<0 THEN continue ELSE sum=sum+num END IF END WHILE PRINT sum Print sum of N inputs Example: N: 5 User Input 5 4 - 3 (skip) 8 - 9 (skip) Sum of input value is: 17 38

Unconditional Control Statements: continue Example 1 : To get N inputs from the user and skip if user inputs negative number then calculate the sum of the user inputs Program: N=int(input("Enter the value of N: ")) i=1 sum=0 while i<=N: num=int(input("Enter the user inputs: ")) i=i+1 if num<0: continue else: sum=sum+num print('The sum of user input is: ',sum) 39

40 Unconditional Control Statements: continue Example 1 : To get N inputs from the user and skip if user inputs negative number then calculate the sum of the user inputs Trace Table Line No N i sum i<=N num Num<0 Output 1 5 2 1 3 4 True 5 5 6 2 7 False 10 5 4 True 5 4 6 3 7 False

Unconditional Control Statements: continue Example 1 : To get N inputs from the user and skip if user inputs negative number then calculate the sum of the user inputs Trace Table Line No N i sum i<=N num Num<0 Output 10 9 4 True 5 - 3 6 4 7 True 10 - 4 True 5 8 6 5 7 False 10 17 41

Unconditional Control Statements: continue Example 1 : To get N inputs from the user and skip if user inputs negative number then calculate the sum of the user inputs Trace Table Line No N i sum i<=N num Num<0 Output 4 True 5 - 9 6 6 7 True 10 - 4 False 11 17 42

Example 2: Write a Python program to print the numbers from 1 to 10. Program:- for i in range(1,11): if i==5: continue print(i) print(“Done”) Unconditional Statement : Continue Output 1 2 3 4 6 7 8 9 10 Done 43

Unconditional Statement : Continue i i==5 Output Output 1 False 1 2 False 2 3 False 3 4 False 4 5 True 6 False 6 7 False 7 8 False 8 9 False 9 10 False 10 11 Done Example 2: Write a Python program to print the numbers from 1 to 10. 44

Pass statement is the statement that are syntactically used to not execute the code. The pass statement does noting. Syntax:- pass Unconditional Statement : Pass 45

Example 1: Write a Python program to print the numbers from 1 to 10. Program:- for i in range(1,11): if i==5: pass print(i) print(“Done”) Unconditional Statement : Pass Output 1 2 3 4 5 6 7 8 9 10 Done 46

Unconditional Statement : Pass i i==5 Output Output 1 False 1 2 False 2 3 False 3 4 False 4 5 True 5 6 False 6 7 False 7 8 False 8 9 False 9 10 False 10 11 Done Example 1: Write a Python program to print the numbers from 1 to 10. 47

A function is block of code which is used to perform a particular task when it is called . Functions are used to perform certain actions, and they are important for reusing code : Define the code once , and use it many times. Function: Introduction 48

Need for Function : Function simplifies the process of program development . Functions provide better modularity and have a high degree of code reuse . Advantages of Function: Reducing duplication of code Decomposing complex problems into simpler pieces Improving clarity of the code Reuse of code Function: Introduction 49

Depending on whether a function is predefined or created by programmer ; there are two types of function: Build- in Function or Library function: Programmer can use library function by invoking function directly ; they don't need to write it themselves. Python has several functions that are readily available for use . Example : print(), range(), format(), abs(), round(), and etc., User- defined Function : The function created by the user according to the need . Function: Introduction 50

Build- in Function Example : The round() function returns a floating-point number rounded to the specified number of decimals. Syntax: round(number, ndigits) The round() function takes two parameters : number - the number to be rounded ndigits (optional) - number up to which the given number is rounded; defaults to Program: # for integers print(round(10)) #10 # for floating point print(round(10.7)) #11 print(round(5.5)) #6 print(round(2.67)) #3 print(round(2.678,2)) #2.68 51

Function Definition: It is a part where we define the operation of a function . It consists of the declarator followed by the function body. Defining a function means, specifying its name , parameters that are expected, and the set of instructions . In Python a function is defined using the def keyword Function: Elements 52

Function Definition:- Function : Defining a Function Example:- # Function Definition def add(a,b): sum=a+b return sum 53

Function : Calling a Function Function Call:- Defining a function means, specifying its name, parameters that are expected, and the set of instructions. Once the basic structure of a function is finalized, it can be executed by calling it. The function call statement invokes the function. Syntax:- function_name(variable1, variable2,…. ) Example:- # Function Call in the Main Function a=int(input(‘Enter the value of a:’)) b=int(input(‘Enter the value of b:’)) res=add(a,b) #The function with the name add is called print(res) 54

Function Call: Syntax: function_name(variable1, variable2,…. ) Example: Function: Elements 55

Function Call:- When a function is invoked, the program control jumps to the called function to execute the statements that are in the part of that function. Once the called function is executed the program control passes back to the calling function. The function that returns the value back to the calling function is known as Fruitful function. Function : Calling a Function # Function Call or Calling Function a=int(input(‘Enter the value of a:’)) b=int(input(‘Enter the value of b:’)) res=add(a,b) print(res) Example:- # Function Definition or Called Function 1. def add(a,b): sum=a+b return sum 56

Parameters:- Parameters are the variables which is used to store the values. Types of Parameters:- Actual Parameter – Parameters used in the function call or calling function. Formal Parameter – Parameters used in the function definition or called function. During program execution, the values in the actual parameter is assigned to the formal parameter. Function : Parameters 57

Example 1 : Python program to find cube of a given number using function Program: ( cube.py ) Function # Sub Function or Called Function def cube(x): return x*x*x # Calling Function n=int(input(‘Enter the value of n:’)) result=cube(n) print(“The Cube is:”, result) Output Enter the value of n: 10 The Cube is: 1000 58

Fruitful Functions:- A fruitful function is one in which there is a return statement with an expression . This means that a fruitful function returns a value that can be utilized by the calling function for further processing. The return Statement:- The return statement is used to return value from the called function to the calling function. A return statement with no argument returns none to the calling function. Syntax: 59 Fruitful Functions return expression

Example: Python program to check whether a given number is odd or even using functions. Fruitful Functions Input Processing Output Prompt the user to enter a number Main Function:- READ a CALL the function evenodd(a) and pass the value of ‘a’ from the calling function to the called function. SET the value obtained from the called function to res IF res==1 THEN PRINT “Number is Even” IF res==- 1 THEN PRINT “Number is Odd” Sub Function:- evenodd(a) GET the value from calling function as a IF a%2==0 THEN RETURN the value as 1 to the calling function ELSE RETURN the value as - 1 to the calling function Print the entered number as odd or even 60

Example: Python program to check whether a given number is odd or even using functions. Program:- def evenodd(a): if(a%2==0): return 1 else: return - 1 a=int(input(“Enter the number”)) res=evenodd(a) if(res==1): print(“Number is even”) if(res==- 1): print(“Number is odd”) Fruitful Functions Output:- Enter the number 10 Number is even 61

Arguments are the values which are assigned to the parameter. Types of Arguments:- Required argument Keyword argument Default argument Variable – length argument Required Argument:- In Required argument , the arguments are passed to a function in correct positional order. The number of arguments in the function call should exactly match with the number arguments specified in the function definition. 62 Fruitful Functions : Parameters

Example: Python program to return the average of its arguments. Program:- def avg(n1,n2): res=(n1+n2)/2 return(res) n1=int(input(“Enter the first no:”)) n2=int(input(“Enter the second no:”)) print(“AVERAGE = ”, avg(n1,n2)) 63 Fruitful Functions : Parameters Output:- Enter the first no: 6 Enter the second no: 4 AVERAGE = 5

Keyword Argument:- In Keyword Argument, the order (or the position) of the arguments can be changed. The values are not assigned to arguments according to their position but based on their name (or keyword). Example 1: Python program to print the employee details using function. Program:- def display(name, age, salary): print(“Name: ”, name) print(“Age: ”, age) print(“Salary: ”, salary) return n=“XYZ” a=35 s=20000 display(salary=s, name=n, age=a) 64 Fruitful Functions : Parameters Output:- Name: XYZ Age: 35 Salary: 20000

Example 2: Python program to print the person information using function. Program:- def printinfo(name, age): print(“This prints a passed info into this function”) print ("Name: ", name) print ("Age: ", age) return printinfo(age=50, name=“miki”) Fruitful Functions : Parameters Output:- This prints a passed info into this function Name: miki Age: 50 65

Default Argument:- Python allows users to specify function arguments that can have default values. Default value to an argument is provided using the assignment operator (=). Default argument assumes a default value, if a value is not provided in the function call for the argument. Example 1: Python program to print the student details using function. Program:- def display(name, course=“BTech”): print(“Name: ”, name) print(“Course: ”, course) return display(course=“BCA”, name=“Arav”) display(name=“Reyansh”) Fruitful Functions : Parameters Output:- Name: Arav Course: BCA Name: Reyansh Course: BTech 66

Variable- length Arguments In some situations, it is not known in advance that how may arguments will be passed to a function. In such cases, Python allows programmers to make function calls with arbitrary number of arguments. When we use arbitrary arguments or variable length arguments, then the function definition uses an asterisk(*) before the parameter name. Syntax:- def functionname([arg1, arg2,….],*var_arg_tuple): function statements return [expression] Fruitful Functions : Parameters 67

Fruitful Functions : Parameters Example 2: Python program to print the sum of two numbers from the entered input. Program:- def sum(a,b,*var): sum=a+b for i in var: print(i) return(sum) print(sum(10,20,30,40,50)) Output:- 30 40 50 30 68

Fruitful Functions : Parameters Example : Python program to print the arbitrary key word arguments and positional argument by the entered input. Program:- def sum(*var,**res): for i in var: print(i) for key,value in res.items(): print(key,":",value) return print(sum(10,20,30,40,50,greeting="HI",a=10)) Output:- 10 20 30 40 50 greeting : HI a : 10 None 69

map() map() returns a map object(which is an iterator) as a result after applying the given function to each item of a given iterable (list, tuple, etc). Example:- def square(x): return x * x Syntax:- map(function_name, iterables) Output:- [1,4,9,16,25] numbers = [1, 2, 3, 4, 5] squared_numbers = map(square, numbers) print(list(squared_numbers)) 70

map() map() returns a map object(which is an iterator) as a result after applying the given function to each item of a given iterable (list, tuple, etc). Example:- def square(x): return x * x Syntax:- map(function_name, iterables) Output:- [1,4,9,16,25] numbers = [1, 2, 3, 4, 5] squared_numbers = map(square, numbers) print(list(squared_numbers)) 71

72 filter() The filter() method filters the given sequence with the help of a function. Example:- def is_even(x): return x % 2 == numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(filter(is_even, numbers))) Syntax:- filter(function_name, iterables) Output:- [2,4,6,8,10]

73 reduce() reduce() is used to apply a function to an iterable and reduce it to a single cumulative value. It is a part of functools module. Example:- import functools def add(x, y): return x + y numbers = [1, 2, 3, 4, 5] sum_of_numbers = functools.reduce(add, numbers) print(sum_of_numbers) Syntax:- functools.reduce(function, iterables) Output:- 15

Lambda() Lambda() are the anonymous function, which means the function without a name. Lambda function takes any number of arguments but can have only one expression. Example:- add=lambda x,y:x+y print(add(2,3)) Syntax:- lambda parameters : expression Output:- 5 74

Lambda() Example 1:- numbers = [1, 2, 3, 4, 5] print(list(map(lambda x: x * 2,numbers))) Example 2:- numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] filtered_numbers = filter(lambda x: x % 2 == 0, numbers) print(list(filtered_numbers)) Output:- [2,4,6,8,10] 75 Output:- [2,4,6,8,10]

Lambda() Example 3:- import functools numbers = [1, 2, 3, 4, 5] sum_of_numbers = functools.reduce(lambda x, y: x + y, numbers) print(sum_of_numbers) Output:- 15 76

Recursive function is defined as a function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself. Every recursive function has major two cases., Base case – The problem is simple enough to be solved directly without making any further calls to the same function. Recursive case – First the problem is divided into simpler sub- parts. Second, the function calls itself with the sub- parts of the problem obtained in the first step. Third, the result is obtained by combining the solutions of simpler sub- parts. Recursion is based on divide and conquer technique for problem solving. Function : Recursion 77

Example 1 :Python program to find exponentiation of given number using recursion Program: ( exp.py ) Function : Recursion # Sub Function or Called Function 1. def exp(base, pow): if(pow==0): return 1 else: return (base*exp(base, pow- 1)) # Main Function or Calling Function base=int(input(‘Enter the base No:’)) power=int(input(‘Enter the power:’)) print(“Result=”, exp(base, pow)) Output Enter the base No: 2 Enter the power: 3 8 78

Example 2 :Python program to find fibonacci series using recursion Program: ( fibo.py ) Function : Recursion # Sub Function or Called Function 1. def fibonacci(n): if(n<=1): return n else: 5. return (fibonacci(n-1)+fibonacci(n- 2)) # Main Function or Calling Function num=int(input(‘Enter the term:’)) if num<=0: print(“Please enter the positive integer”) else: for i in range(0, num): print(fibonacci(i)) Output Enter the term: 5 1 1 2 3 79

Illustrative Programs Financial Application:- (Example 1) Develop Python Code for the Financial Application Enter the Product name: Pen Enter the quantity of an item sold: 5 Enter the value of an item: 2 Enter the discount percentage: 2 Enter the tax: 2 *******************BILL***************** Quantity sold: 5 Price per item: 2 Amount: 10.0 Discount: - 0.2 Total: 9.8 Tax: +0.196 Amount to be Paid : 9.996 80

Illustrative Programs Financial Application:- (Example 2) Develop Python Code for the Financial Application 81

Illustrative Programs Sandwich Vowel:- def sandwich_vowel(string, sandwich_char): vowels = 'aeiouAEIOU' result = '' for char in string: if char in vowels: result += sandwich_char + char + sandwich_char else: result += char return result text = "hello" sandwiched_text = sandwich_vowel(text, "*") print(sandwiched_text) Output:- h*e*ll*o* 82

Illustrative Programs Sandwich Vowel:- def isVowel(x): if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'): return True else: return False 83

Illustrative Programs Sandwich Vowel:- def updateSandwichedVowels(a): n = len(a) updatedString = "" for i in range(0, n, 1): if (i == or i == n - 1): updatedString += a[i] continue if (isVowel(a[i]) == True and isVowel(a[i - 1]) == False and isVowel(a[i + 1]) == False): continue updatedString += a[i] return updatedString 84

Illustrative Programs Sandwich Vowel:- str = "vowel" UpdatedString = updateSandwichedVowels(str) print(UpdatedString) Output:- vwl 85

Illustrative Programs Chocolate Distribution Algorithm:- Given an array of n integers where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: Each student gets one packet. The difference between the number of chocolates in the packet with maximum chocolates and packet with minimum chocolates given to the students is minimum. Examples: Input : arr[] = {7, 3, 2, 4, 9, 12, 56} , m = 3 Output: Minimum Difference is 2 Explanation: We have seven packets of chocolates and we need to pick three packets for 3 students If we pick 2, 3 and 4, we get the minimum difference between maximum and minimum packet sizes. Input : arr[] = {3, 4, 1, 9, 56, 7, 9, 12} , m = 5 Output: Minimum Difference is 6 Explanation: The set goes like 3,4,7,9,9 and the output is 9- 3 = 6 86

Illustrative Programs Chocolate Distribution Algorithm:- 87

88 Illustrative Programs Chocolate Distribution Algorithm:- def findMinDiff(arr, n, m): if (m==0 or n==0): return arr.sort() if (n < m): return - 1 min_diff = arr[n- 1] - arr[0] for i in range(len(arr) - m + 1): min_diff = min(min_diff , arr[i + m - 1] - arr[i]) return min_diff arr = [12,4,7,9,2,23,25] m = 4 n = len(arr) print("Minimum difference is", findMinDiff(arr, n, m)) Output:- Minimum difference is 7

Al Sweigart, "Automate the Boring Stuff with Python: Practical Programming for Total Beginners," 2nd Edition, No Starch Press, 2019 Liang Y. Daniel, “Introduction to Programming Using Python”, Pearson Education, 2017 Jake VanderPla, “Python Data Science Handbook,” O’Reilly (https://jakevdp.github.io/PythonDataScienceHandbook) William S Vincent, “Django for Beginners: Build Websites with Python and Django,” Welcome to code Publishers, 2020. Reference Books

Reference Books Robert Sedgewick, Kevin Wayne, Robert Dondero, "Introduction to Programming in Python: An Inter- Disciplinary Approach," Pearson India Education Services Pvt. Ltd., 2016 Allen B. Downey, "Think Python: How to Think Like a Computer Scientist," Second edition, Updated for Python 3, Shroff O'Reilly Publishers, 2016 Timothy A. Budd," Exploring Python," Mc- Graw Hill Education (India) Private Ltd., 2015
Tags