SlideShare a Scribd company logo
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:
1.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 Modes
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 Modes
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 Interactive 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
Integer values can be represented in following ways
-Decimal form (Base 10) - 0 to 9
-Binary form (Base 2) - 0, 1, literals prefix starts with 0B or 0b
-Octal form (Base 8) - 0 to 7, literals prefix starts with 0o or 0O
- Hexadecimal (Base 16) - 0 to 9, A to F, literals prefix starts with 0X or 0x
Numeric Data Type:-
Integer:-
Eg:-
Data Types
Float values are represented by a decimal point value.
- Eg:- 2.5, -28.98, etc
The floating point values can also represented by a exponential form.
- Eg:- 1.2e3, etc
Numeric Data Type:-
Float:-
Eg:-
Data Types
A complex number is represented by a complex class.
It is specified as (real part) + (imaginary part)j. For example:- – 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
heterogeneou
s 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 0 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 0 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.3333333
333333335 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
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. 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
1. Identity Operators
❑ We can use identity operators for address comparison.
❑ 2 identity operators are available
2. is
3. 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
1. Identity Operators
2. 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:
State
ments
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:
1. number = int(input("Enter a number:n"))
2. if (number % 2) == 0:
3. print(number," is Even number")
4. else:
5. 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 “if Statement” executes the
statements only if the condition is True.
• “elif Statement” provides an alternative possibility for the “if
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:
1. num=int(input("Enter any number:n"))
2. if num > 0:
3. print(num,"is Positive number")
4. elif num == 0:
5. print(num,"is Zero")
6. else:
7. 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:
1. a=int(input("Enter the first number: "))
2. b=int(input("Enter the second number: "))
3. c=int(input("Enter the third number: "))
4. if a>b:
5. if a>c:
6. print(a,"is the greatest number than",b,"and",c)
7. else:
8. print(c,"is the greatest number than",a,"and",b)
9. elif b>c:
10. print(b,"is the greatest number than",a,"and",c)
11. else:
12. 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
1. Write a program to check leap year or not.
2.Write a program to display “Hello” if a number entered
by the user is multiple of 5 otherwise print “Bye”.
3.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.
4.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:
1. N=int(input('Enter the value of N: '))
2. i=1 # initialization
3. while i<=N: # Condition
4. print(i)
5. 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
C
OMP
UTE
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:
1. N = int(input("Enter a number: ")) # To take input from the user
2. factorial = 1
3. if N < 0: # check if the number is negative, positive or
zero
4. print("Sorry, factorial does not exist for negative numbers")
5. elif N == 0:
6. print("The factorial of 0 is 1")
7. else:
8. for i in range(1,N + 1):
9. factorial = factorial*i
10. 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:
1. i=1
2. while i<=10:
3. print(i)
4. if i==3:
5. break
6. i=i+1
7. 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 0
WHILE i<=N
READ num
IF num==-1 THEN
break
ELSE
su
m=su
m+n
um
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:
1. N=int(input("Enter the value of N"))
2. i=1
3. sum=0
4. while i<=N:
5. num=int(input("Enter the user inputs"))
6. if num==-1:
7. break
8. else:
9. sum=sum+num
10. i=i+1
11. 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 0
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 0
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:
1. N=int(input("Enter the value of N: "))
2. i=1
3. sum=0
4. while i<=N:
5. num=int(input("Enter the user inputs: "))
6. i=i+1
7. if num<0:
8. continue
9. else:
10. sum=sum+num
11. 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 0
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 0
Program:
1. # for integers
2. print(round(10)) #10
3. # for floating point
4. print(round(10.7)) #11
5. print(round(5.5)) #6
6. print(round(2.67)) #3
7. 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
1. def add(a,b):
2. sum=a+b
3. 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
1. a=int(input(‘Enter the value of a:’))
2. b=int(input(‘Enter the value of b:’))
3. res=add(a,b) #The function
with the name add is called
4. 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
1. a=int(input(‘Enter the value of a:’))
2. b=int(input(‘Enter the value of b:’))
3. res=add(a,b)
4. print(res)
Example:-
# Function Definition or Called
Function
1. def add(a,b):
2. sum=a+b
3. 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 numberusing function
Program: (cube.py)
Function
# Sub Function or Called
Function
1. def cube(x):
2. return x*x*x
# Calling Function
1. n=int(input(‘Enter the value of n:’))
2. result=cube(n)
3. 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(sa 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 == 0
numbers = [1, 2, 3,
4, 5, 6, 7, 8, 9, 10]
print(list(filter(is_e
ven, 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)
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(lambd
a 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):
2. if(pow==0):
3. return 1
4. else:
5. return (base*exp(base, pow-1))
# Main Function or Calling Function
1. base=int(input(‘Enter the base No:’))
2. power=int(input(‘Enter the power:’))
3. 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):
2. if(n<=1):
3. return n
4. else:
5. return (fibonacci(n-1)+fibonacci(n-2))
# Main Function or Calling Function
1. num=int(input(‘Enter the term:’))
2. if num<=0:
3. print(“Please enter the positive integer”)
4. else:
5. for i in range(0, num):
6. print(fibonacci(i))
Output
Enter the term: 5
0 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
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 == 0 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:
1. Each student gets one packet.
2.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 0
arr.sort()
if (n < m):
retur
n -1
min_dif
f = arr[n-
1] - arr[0]
for i in
range(len(
arr) - m +
1):
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
Ad

More Related Content

Similar to Python Programming for problem solving.pptx (20)

Pyhton problem solving introduction and examples
Pyhton problem solving introduction and examplesPyhton problem solving introduction and examples
Pyhton problem solving introduction and examples
ssuser65733f
 
Unit 2 python
Unit 2 pythonUnit 2 python
Unit 2 python
praveena p
 
Python Basics Understanding Variables.pdf
Python Basics Understanding Variables.pdfPython Basics Understanding Variables.pdf
Python Basics Understanding Variables.pdf
codingmaster021
 
Python Basics Understanding Variables.pdf
Python Basics Understanding Variables.pdfPython Basics Understanding Variables.pdf
Python Basics Understanding Variables.pdf
codingmaster021
 
1. python programming
1. python programming1. python programming
1. python programming
sreeLekha51
 
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptxpython notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
yuvarajkumar334
 
1-Introduction to Python, features of python, history of python(1).pptx
1-Introduction to Python, features of python, history of python(1).pptx1-Introduction to Python, features of python, history of python(1).pptx
1-Introduction to Python, features of python, history of python(1).pptx
MAHESWARIS55
 
Introduction to Python Programming .pptx
Introduction to  Python Programming .pptxIntroduction to  Python Programming .pptx
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
Chariza Pladin
 
Lec1- Python Basics .pptx rrev python Funda
Lec1- Python Basics .pptx rrev python FundaLec1- Python Basics .pptx rrev python Funda
Lec1- Python Basics .pptx rrev python Funda
pm945858
 
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
Scode Network Institute
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Saravanan T.M
 
Python
PythonPython
Python
Dr. SURBHI SAROHA
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Mohd Sajjad
 
Python 3.x quick syntax guide
Python 3.x quick syntax guidePython 3.x quick syntax guide
Python 3.x quick syntax guide
Universiti Technologi Malaysia (UTM)
 
UNIT 1 .pptx
UNIT 1                                                .pptxUNIT 1                                                .pptx
UNIT 1 .pptx
Prachi Gawande
 
Python Training in Chandigarh
Python Training in ChandigarhPython Training in Chandigarh
Python Training in Chandigarh
Excellence Technology
 
Chapter 1-Introduction and syntax of python programming.pptx
Chapter 1-Introduction and syntax of python programming.pptxChapter 1-Introduction and syntax of python programming.pptx
Chapter 1-Introduction and syntax of python programming.pptx
atharvdeshpande20
 
Python_Unit_1.pdf
Python_Unit_1.pdfPython_Unit_1.pdf
Python_Unit_1.pdf
alaparthi
 
Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
AliMohammadAmiri
 
Pyhton problem solving introduction and examples
Pyhton problem solving introduction and examplesPyhton problem solving introduction and examples
Pyhton problem solving introduction and examples
ssuser65733f
 
Python Basics Understanding Variables.pdf
Python Basics Understanding Variables.pdfPython Basics Understanding Variables.pdf
Python Basics Understanding Variables.pdf
codingmaster021
 
Python Basics Understanding Variables.pdf
Python Basics Understanding Variables.pdfPython Basics Understanding Variables.pdf
Python Basics Understanding Variables.pdf
codingmaster021
 
1. python programming
1. python programming1. python programming
1. python programming
sreeLekha51
 
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptxpython notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
python notes for MASTER OF COMPUTER APPLIICATION_ppt.pptx
yuvarajkumar334
 
1-Introduction to Python, features of python, history of python(1).pptx
1-Introduction to Python, features of python, history of python(1).pptx1-Introduction to Python, features of python, history of python(1).pptx
1-Introduction to Python, features of python, history of python(1).pptx
MAHESWARIS55
 
Introduction to Python Programming .pptx
Introduction to  Python Programming .pptxIntroduction to  Python Programming .pptx
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
Chariza Pladin
 
Lec1- Python Basics .pptx rrev python Funda
Lec1- Python Basics .pptx rrev python FundaLec1- Python Basics .pptx rrev python Funda
Lec1- Python Basics .pptx rrev python Funda
pm945858
 
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
Scode Network Institute
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Mohd Sajjad
 
Chapter 1-Introduction and syntax of python programming.pptx
Chapter 1-Introduction and syntax of python programming.pptxChapter 1-Introduction and syntax of python programming.pptx
Chapter 1-Introduction and syntax of python programming.pptx
atharvdeshpande20
 
Python_Unit_1.pdf
Python_Unit_1.pdfPython_Unit_1.pdf
Python_Unit_1.pdf
alaparthi
 

Recently uploaded (20)

Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Ad

Python Programming for problem solving.pptx

  • 1. Mrs. M. Nisha Assistant Professor Department of CSE Akshaya College of Engineering and Technology Python for Everyone
  • 2. 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
  • 3. Introduction Python is a popular programming language for several reasons: 1.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.
  • 6. Python Environmental Setup Step 1: Download Python Installer https://www.python.org/downloads/
  • 7. Python Environmental Setup Step 2: Run the Executable Installer
  • 8. Python Interpreter Modes 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.
  • 9. Python Interpreter Modes 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
  • 10. Python Interactive 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.
  • 11. Python Interactive Mode Python Interactive Mode : Example
  • 12. 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
  • 13. Python Script Mode Python Script Mode : Example
  • 14. 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
  • 15. 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.
  • 16. 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.
  • 17. 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.
  • 18. 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.
  • 19. 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
  • 20. 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.
  • 23. Data Types Python data type is used to identify the type of data.
  • 24. 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
  • 25. Data Types Integer values can be represented in following ways -Decimal form (Base 10) - 0 to 9 -Binary form (Base 2) - 0, 1, literals prefix starts with 0B or 0b -Octal form (Base 8) - 0 to 7, literals prefix starts with 0o or 0O - Hexadecimal (Base 16) - 0 to 9, A to F, literals prefix starts with 0X or 0x Numeric Data Type:- Integer:- Eg:-
  • 26. Data Types Float values are represented by a decimal point value. - Eg:- 2.5, -28.98, etc The floating point values can also represented by a exponential form. - Eg:- 1.2e3, etc Numeric Data Type:- Float:- Eg:-
  • 27. Data Types A complex number is represented by a complex class. It is specified as (real part) + (imaginary part)j. For example:- – 2+3j Numeric Data Type:- Complex Number:- Eg:
  • 28. Data Types Boolean Data Type:- Boolean data type is represented by the boolean values. Boolean values are represented by True (1), False (0) Eg:-
  • 29. 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"""
  • 30. Data Types Examples of String Representation:-
  • 31. Data Types Examples of String Memory Allocation:-
  • 32. Data Types Examples of String Indexing:-
  • 33. 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 “[ : ]”.
  • 34. Data Types Sequence:- List:- List is a mutable & ordered collection of elements of heterogeneou s data type. In list, the elements are separated by commas and that are enclosed within square bracket “[ ]” Eg:
  • 35. Data Types Example for List Indexing:- In list, the elements are represented with the index value from 0 to n-1. Eg:
  • 36. Data Types Example for List Mutablility:- Eg:
  • 37. 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:
  • 38. Data Types : Sequence Example for Tuple Representation:-
  • 39. Data Types Example for Tuple Indexing:- In tuple, the elements are represented with the index value from 0 to n-1. Eg:
  • 40. Data Types Example for Tuple Immutablility:- Eg:
  • 41. Data Types Set:- Set is an unordered, unindexed & unchangeable collection of elements. Eg:-
  • 42. Data Types Set:- Set is an unordered, unindexed & unchangeable collection of elements. Eg:-
  • 43. 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:-
  • 44. Data Types Example for Dictionary Mutablility:- Eg:
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. Constant Expression ❑Constant expressions are expressions having constant values only. Constant Expression x = 15 + 1.3 print(x) Output 16.3 5
  • 50. Arithmetic Expression An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis.The arithmetic operators are 6
  • 51. 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.3333333 333333335 7
  • 52. 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
  • 53. 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
  • 54. 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
  • 55. 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
  • 56. 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
  • 57. 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
  • 58. Operators ❑ Operator is a symbol that performs certain operations. ❑ Python provides the following set of operators 1. Arithmetic Operators 2. Relational Operators or Comparison Operators 3. Logical operators 4. Bitwise operators 5. Assignment operators 6. Special operators 1
  • 79. Special operators 1. Identity Operators ❑ We can use identity operators for address comparison. ❑ 2 identity operators are available 2. is 3. 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 1. Identity Operators 2. Membership operators 22
  • 80. Special operators - Example 23
  • 81. 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
  • 82. 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:
  • 83. Operators Precedence - Example 26 .
  • 84. 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
  • 85. 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
  • 86. • 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
  • 87. • 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
  • 88. • 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
  • 89. • 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
  • 90. • 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: State ments 7
  • 91. 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
  • 92. Example 1: To check whether the given number is odd or even number Program: 1. number = int(input("Enter a number:n")) 2. if (number % 2) == 0: 3. print(number," is Even number") 4. else: 5. 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 - -
  • 93. • Chained conditional Statements are also known as if–elif-else Statement, in which the “if Statement” executes the statements only if the condition is True. • “elif Statement” provides an alternative possibility for the “if 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
  • 95. 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
  • 96. Selection : If – elif - else Statement 13 Program: 1. num=int(input("Enter any number:n")) 2. if num > 0: 3. print(num,"is Positive number") 4. elif num == 0: 5. print(num,"is Zero") 6. else: 7. 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
  • 97. • 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
  • 98. 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
  • 99. Nested If Statement Example 1: To find the greatest among three numbers Program: 1. a=int(input("Enter the first number: ")) 2. b=int(input("Enter the second number: ")) 3. c=int(input("Enter the third number: ")) 4. if a>b: 5. if a>c: 6. print(a,"is the greatest number than",b,"and",c) 7. else: 8. print(c,"is the greatest number than",a,"and",b) 9. elif b>c: 10. print(b,"is the greatest number than",a,"and",c) 11. else: 12. print(c,"is the greatest number than",a,"and",b) 16
  • 100. 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
  • 101. Practice Exercises : Conditionals 1. Write a program to check leap year or not. 2.Write a program to display “Hello” if a number entered by the user is multiple of 5 otherwise print “Bye”. 3.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. 4.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
  • 102. • 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
  • 103. • 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
  • 104. 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: 1. N=int(input('Enter the value of N: ')) 2. i=1 # initialization 3. while i<=N: # Condition 4. print(i) 5. i=i+1 # Increment
  • 105. 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
  • 106. • 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
  • 107. 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 C OMP UTE Print factorial of N Example: N=5 The factorial of 5 is 120 24
  • 108. Iteration : For Loop Statement Example 1: Calculate the factorial of a given number Program: 1. N = int(input("Enter a number: ")) # To take input from the user 2. factorial = 1 3. if N < 0: # check if the number is negative, positive or zero 4. print("Sorry, factorial does not exist for negative numbers") 5. elif N == 0: 6. print("The factorial of 0 is 1") 7. else: 8. for i in range(1,N + 1): 9. factorial = factorial*i 10. print("The factorial of",N,"is",factorial) 25
  • 109. 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
  • 110. 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
  • 111. • 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
  • 112. • 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
  • 113. • 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
  • 114. 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
  • 115. 32 Unconditional Control Statement : Break Program: 1. i=1 2. while i<=10: 3. print(i) 4. if i==3: 5. break 6. i=i+1 7. 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
  • 116. 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 0 WHILE i<=N READ num IF num==-1 THEN break ELSE su m=su m+n um 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
  • 117. 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: 1. N=int(input("Enter the value of N")) 2. i=1 3. sum=0 4. while i<=N: 5. num=int(input("Enter the user inputs")) 6. if num==-1: 7. break 8. else: 9. sum=sum+num 10. i=i+1 11. print('The sum of user input is: ',sum) 34
  • 118. 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 0 4 True 5 5 6 False 7 5 8 2 4 True 5 8 6 False 7 13
  • 119. 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
  • 120. • 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
  • 121. 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 0 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
  • 122. 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: 1. N=int(input("Enter the value of N: ")) 2. i=1 3. sum=0 4. while i<=N: 5. num=int(input("Enter the user inputs: ")) 6. i=i+1 7. if num<0: 8. continue 9. else: 10. sum=sum+num 11. print('The sum of user input is: ',sum) 39
  • 123. 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 0 4 True 5 5 6 2 7 False 10 5 4 True 5 4 6 3 7 False
  • 124. 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
  • 125. 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
  • 126. 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
  • 127. 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
  • 128. • 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
  • 129. 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
  • 130. 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
  • 131. • 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
  • 132. 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
  • 133. • 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
  • 134. 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 0 Program: 1. # for integers 2. print(round(10)) #10 3. # for floating point 4. print(round(10.7)) #11 5. print(round(5.5)) #6 6. print(round(2.67)) #3 7. print(round(2.678,2)) #2.68 51
  • 135. 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
  • 136. Function Definition:- Function : Defining a Function Example:- # Function Definition 1. def add(a,b): 2. sum=a+b 3. return sum 53
  • 137. 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 1. a=int(input(‘Enter the value of a:’)) 2. b=int(input(‘Enter the value of b:’)) 3. res=add(a,b) #The function with the name add is called 4. print(res) 54
  • 139. 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 1. a=int(input(‘Enter the value of a:’)) 2. b=int(input(‘Enter the value of b:’)) 3. res=add(a,b) 4. print(res) Example:- # Function Definition or Called Function 1. def add(a,b): 2. sum=a+b 3. return sum 56
  • 140. 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
  • 141. Example 1: Python program to find cube of a given numberusing function Program: (cube.py) Function # Sub Function or Called Function 1. def cube(x): 2. return x*x*x # Calling Function 1. n=int(input(‘Enter the value of n:’)) 2. result=cube(n) 3. print(“The Cube is:”, result) Output Enter the value of n: 10 The Cube is: 1000 58
  • 142. 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
  • 143. 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
  • 144. 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
  • 145. • 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
  • 146. 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
  • 147. 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(sa 64 Fruitful Functions : Parameters Output:- Name: XYZ Age: 35 Salary: 20000
  • 148. 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
  • 149. 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
  • 150. 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
  • 151. 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
  • 152. 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
  • 153. 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
  • 154. 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
  • 155. 72 filter() • The filter() method filters the given sequence with the help of a function. Example:- def is_even(x): return x % 2 == 0 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(filter(is_e ven, numbers))) Syntax:- filter(function_name, iterables) Output:- [2,4,6,8,10]
  • 156. 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) Syntax:- functools.reduce(function, iterables) Output:- 15
  • 157. 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
  • 158. 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]
  • 159. Lambda() Example 3:- import functools numbers = [1, 2, 3, 4, 5] sum_of_numbers = functools.reduce(lambd a x, y: x + y, numbers) print(sum_of_numbers) Output:- 15 76
  • 160. • 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
  • 161. 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): 2. if(pow==0): 3. return 1 4. else: 5. return (base*exp(base, pow-1)) # Main Function or Calling Function 1. base=int(input(‘Enter the base No:’)) 2. power=int(input(‘Enter the power:’)) 3. print(“Result=”, exp(base, pow)) Output Enter the base No: 2 Enter the power: 3 8 78
  • 162. Example 2:Python program to find fibonacci series using recursion Program: (fibo.py) Function : Recursion # Sub Function or Called Function 1. def fibonacci(n): 2. if(n<=1): 3. return n 4. else: 5. return (fibonacci(n-1)+fibonacci(n-2)) # Main Function or Calling Function 1. num=int(input(‘Enter the term:’)) 2. if num<=0: 3. print(“Please enter the positive integer”) 4. else: 5. for i in range(0, num): 6. print(fibonacci(i)) Output Enter the term: 5 0 1 1 2 3 79
  • 163. 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 80
  • 164. Illustrative Programs Financial Application:- (Example 2) Develop Python Code for the Financial Application 81
  • 165. 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
  • 166. 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
  • 167. Illustrative Programs Sandwich Vowel:- def updateSandwichedVowels(a): n = len(a) updatedString = "" for i in range(0, n, 1): if (i == 0 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
  • 168. Illustrative Programs Sandwich Vowel:- str = "vowel" UpdatedString = updateSandwichedVowels(str) print(UpdatedString) Output:- vwl 85
  • 169. 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: 1. Each student gets one packet. 2.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
  • 171. 88 Illustrative Programs Chocolate Distribution Algorithm:- def findMinDiff(arr, n, m): if (m==0 or n==0): return 0 arr.sort() if (n < m): retur n -1 min_dif f = arr[n- 1] - arr[0] for i in range(len( arr) - m + 1): 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
  • 172. 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
  • 173. 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