Module-1 Advance Python
Module-1 Advance Python
1
Module-1
Data types
Operators and Expressions
Input and Output Statements
Control Structures
Selective and Repetitive structures
Introduction to Python
WHAT?
• Created by Guido van Rossum.
• First released in 1991.
3
Why Python?
• Works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
• Simple syntax similar to the English language.
• Less number of lines.
• Prototyping can be very quick.
• Python can be treated in a procedural way, an object-orientated way
or a functional way.
Python Features
Easy to Use:
Python is very easy to use and high level language. Thus it is programmer-friendly language.
Expressive Language:
Python language is more expressive. The sense of expressive is the code is easily understandable.
Interpreted Language:
Python is an interpreted language i.e. interpreter executes the code line by line at a time.
This makes debugging easy and thus suitable for beginners.
Cross-platform language:
Python can run equally on different platforms such as Windows, Linux, Unix , Macintosh etc. Thus, Python is a
portable language.
Free and Open Source:
Python language is freely available(www.python.org).The source-code is also available. Therefore it is open source.
Object-Oriented language:
Python supports object oriented language. Concept of classes and objects comes into existence.
Large Standard Library:
Python has a large and broad library.
GUI Programming:
Graphical user interfaces can be developed using Python.
Integrated:
It can be easily integrated with languages like C, C++, JAVA etc. 5
Limitations of Python
Difficulty in Using Other Languages
The Python lovers become so accustomed to its features and its extensive libraries,
so they face problem in learning or working on other programming languages.
Python experts may see the declaring of cast “values” or variable “types”, syntactic
requirements of adding curly braces or semi colons as an onerous task.
7
Limitations of Python
Gets Slow in Speed
Python executes with the help of an interpreter instead of the compiler, which causes it to
slow down because compilation and execution help it to work normally. On the other hand,
it can be seen that it is fast for many web applications too.
Run-time Errors
The Python language is dynamically typed so it has many design restrictions that are
reported by some Python developers. It is even seen that it requires more testing time, and
the errors show up when the applications are finally run.
Underdeveloped Database Access Layers
As compared to the popular technologies like JDBC and ODBC, the Python’s database
access layer is found to be bit underdeveloped and primitive. However, it cannot be
applied in the enterprises that need smooth interaction of complex legacy data.
8
Users of Python
Science
Software Development
• NASA
• Red Hat
• The National Research Council of Canada
• Nokia
• AlphaGene
• Object Domain
• Applied Maths
9
Release Versions
• Python 2.0.1 – 2001
• Python 2.7 – 2010(Last Stable Version of 2.x series)
• Python 3.0 – 2008(Not Backward compatible with all earlier versions)
• Python 3.7 – June 27, 2018
• Python 3.8.4 – June 30, 2020
• Python 3.9.7 - August 30, 2021
• Python 3.10.5 - June 6, 2022
• Python 3.11.1 - December 6, 2022 – Latest Release
10
Important differences between Python 2.x and Python 3.x
Whenever two integers are divided, you When two integers are divided, you
Division of Integers
get a float value always provide integer value.
Syntax The syntax is simpler and easily The syntax of Python 2 was
understandable. comparatively difficult to understand.
Iteration The new Range() function introduced to In Python 2, the xrange() is used for
perform iterations. iterations.
Colaboratory (short for Colab), a tool for machine learning education and research,
created as a Google research project.
Creating and running Jupyter Notebook on Colab is super easy and it’s free.
You can save your notebook to Google Drive or GitHub and even train your deep
learning on GPU.
Getting Started with Google Colab
https://colab.research.google.com
Watch how it works
https://www.youtube.com/watch?v=i-HnvsehuSw
17
18
Rename your note book with .ipynb
19
Download
or Save
colab
note book
20
Make single note book for all programs in a module
3 programs
• Print Hello
• Add 2 numbers
• Find square root of a number
21
Sharing Your Notebook
• Google Colab also gives us an easy way of sharing our work with others.
This is one of the best things about Colab:
22
Next Time open same notebook and continue
23
Comments in Python
Single line comment:
print ("Hello, Python!”) #first comment
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
24
Representation of Data
• Literal
• Numeric Literal
• String Literals
• Control Characters
• String Formatting
• Variables
• Identifiers
• Operators
• Arithmetic operators
• Expressions and Data Types
• Operator Precedence and Associativity
• Data type
• Mixed Type expressions
25
Numeric Literal
26
Numeric Literal…..
Integer Values:
5 2500 + 2500 -2500
-2,500.125
28
Numeric Literal…..
• >>1/3
• .3333333333333333
• The repeating digit ends after the 16th digit.
29
Built in format function
30
Representation of Data
• String Literals
• A sequence of characters within a pair of matching single or double quotes or triple
quotes
• Ex: ‘Hello’ ‘Smith, John’
“Baltimore, Maryland” ‘ ‘ ‘’
“Jennifer’s friend”
• Convention is use single quotes for delimiting strings
• Type the following in your Jupyter notebook:
• >>> print(‘Hello’) ????? >>> print(‘Let’s Go’) ????
• >>> print(“Hello’) ????? >>> print(“Let’s Go!’) ???
• >>> print(“Let’s Go!”) ????
31
Representation of Data…..
• Representation of Character Values
• Characters are represented using the encoding scheme UTF-8
• an 8 bit encoding scheme compatible with ASCII.
• For example’ is encoded as 01000001(65) and ‘B’ is encoded as
01000010(66) and‘A so on
• ord() function gives the UTF-8 encoding of a given character
• For ex, ord(‘A’) is 65
• The chr() function gives the character for a given encoding value.
• For ex, chr(65) is ‘A’.
32
• Observe the following from the command line
• >>>ord(‘1’) >>>chr(65) >>>chr(97) >>>ord(‘2’)
• ???????? ?????? ?????? ??????
33
Control Characters
• These are nonprinting characters used to control the display of output.
• an escape sequence is a string of two or more characters used to denote
control characters
• ‘\’ serves as the escape character in Python
• For ex, the escape sequence ‘\n’ represents the new line control
character, used to begin a new screen line.
• Ex:
• >>>print(‘Hello\nJenifer’)
Hello
Jenifer
34
Control Characters….
• Explore the results of the following :
• print(‘Hello World\n\n’) ???????
• print(1,’\n’,2,’\n’,3) ???????
• print(‘\nHello World’) ??????
35
Formatting Strings
36
• To center a string use the ‘^’ character
• Default fill character is blank
• A specific fill character can also be specified.
• print(‘Hello World’, format(‘.’, ‘.<30’), ‘Have a Nice day’)
• Output :
• Hello World……………….Have a Nice day
37
An identifier (variable)
38
Identifier names
Python has some rules that you must follow when forming an identifier:
• it may only contain letters (uppercase or lowercase), numbers or the underscore character (_) (no
spaces!).
• it may not start with a number.
• it may not be a keyword.
Syntax error Bad practice, may correct Good practice
Person Record PRcrd PersonRecord
DEFAULT-HEIGHT Default_Ht DEFAULT_HEIGHT
class Class AlgebraCourse
2totalweight num2 total_weight
40
#to get the list of keywords
import keyword
print(keyword.kwlist)
41
Python Variables
• Variable is a name which is used to refer memory location. Variable also known as identifier and used to hold value.
• In Python, we don't need to specify the type of variable because Python is a type infer language and smart enough to get
variable type.
Variable Names
• A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
• the same variable can be associated with values of different types during program execution
• var = 12 integer
• var = 12.45 float
• var = ‘Hello’ string
42
Variable names
Valid variable names
Invalid variable names Camel case:
myvar = "John"
2myvar = "John" myVariableName = "John“
my_var = "John"
my-var = "John"
_my_var = "John"
my var = "John" Snake case:
myVar = "John"
my_variable_name = "John"
MYVAR = "John"
myvar2 = "John"
Casting: If you want to specify the data type of a variable, this can be done with casting.
x = str(3)
y = int(3)
z = float(3)
print(x)
print(y)
print(z)
sides = 4
print( type(sides) )
print( id(sides) )
Output
<class 'int'>
10915392
Mutable and immutable types
44
Output variables
To combine both text and a variable, Python uses the + character:
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
x = "Python is "
y = "awesome"
z=x+y
print(z)
If you try to combine a string and a number, Python will give you an error:
x=5
y = "John"
print(x + y)
Changing an Integer
a=1 a 1
a
b=a 1
b new int object created
by add operator (1+1)
a 2
a = a+1 old reference deleted
by assignment (a=...)
b 1
46
Data types
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
x = str(“23")
#display x:
print(x)
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!") --------- This will throw error
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")------------ This will throw error
Input and Output statement
• Some of the functions like input() and print() are widely used for standard input and output operations respectively.
• Input function is used to read a line from the keyboard.
• The input() function allows user input.
• The input function returns all inputs as strings.
• For numeric inputs, the response of the input() must be converted to appropriate type.
Syntax:input(prompt)
Parameter Description
prompt A String, representing a default message before the input.
Variable_name=input(“String”)
Write a simple Python script to calculate age based on the user's input for their birth year.
birth_year=int(input("Enter birth year: " ))
age=2023-birth_year
print(age) 52
Operators in Python
53
Operators
Unary and binary arithmetic operators
Arithmetic Meaning Example Result
Operator
-x negation -10 -10
x+y addition 10 + 25 35
x–y subtraction 10 – 25 -15
x*y multiplication 10 * 5 50
x/y division 25/10 2.5
x // y truncating 25 // 10 25// 10.0 2 2.0
division
x%y modulus 25 % 10 5
x ** y exponentiation 10 ** 2 100
54
Expressions
• a combination of operands (or a single operand) with operators that
evaluates to a value.
• If it evaluates to a numeric value it is known as arithmetic expression
55
Operator Precedence
Operator Operator Name
() Parenthesis
** Exponentiation
- Unary minus
*, /, //, % Multiply, Divide, Floor Division, Modulus
+, - Addition, Subtraction
>, >=, <=, <, ==, != Relational Operators
=, %=, /=, //=, -=, +=, *=, **= Assignment Operators
is, is not Identity Operators
not in, in Membership Operators
or Logical OR
and Logical AND
not Logical NOT
56
Operator Associativity
Operator Operator Name
** Right to Left
- Left to Right
+, - Left to Right
or Left to Right
57
Operator Precedence and Associativity
• Try the following:
2 + 3 * 4 ????? 2 * 3//4 ???? 2 * 3 + 4 ?????
58
Mixed Type Expressions, Coercion and Type
Conversion
1. Arithmetic Operators
2. Assignment Operators
3. Unary Operators
4. Relational Operators
5. Logical Operators
6. Boolean Operators
7. Membership Operators
8. Identity Operators
60
1. Arithmetic Operators
Operator Meaning a = 13, b e Result
61
num1 = eval(input("Enter the first number: "))
Program 1:Write a program that prompts a user to enter two different numbers. Perform basic arithmetic operations based on the choices.
-= z -= x z = 5 – 20 -15
=> z = z – x
*= z *= x z = 5 *20 100
=> z = z * x
/= z /= x z = 5 / 20 0.25
=> z = z / x
%= z %= x z = 5 % 20 5
=> z = z % x
//= z //= x z = 5 // 20 0
=> z = z // x
64
Example: x=5
x=5 x /= 3
print(x) print(x)
x=5 x=5
x += 3 x%=3
print(x) print(x)
x=5 x=5
x -= 3 x//=3
print(x) print(x)
x=5 x=5
x *= 3 x **= 3
print(x) print(x)
65
3. Unary Minus Operators
num = -10
num = -num
print(num) #10
66
4. Relational Operators
• Relational operators are used for comparing the values. The relational operators are also known as Comparison
Operators
• Relational Operators in python compare the operand values on either side.
• The relational operators in Python return a boolean value, i.e., either True or False based on the value of operands.
Operator Meaning a = 13, b = 2 Result
== Equal To a == b False
67
5. Logical Operators
Logical operators are used to combine conditional statements:
Example:x = 5
print(x > 3 and x < 10)
x=5
print(x > 3 or x < 4)
x=5
print(not(x > 3 and x < 10))
68
6. Boolean Operators
69
7. Membership Operators
70
Examples:
a=10
l=[10,23,45]
a in l
Output: True fruit='pineapple‘
‘papp' not in fruit
fruit='pineapple‘ Output: True
'apple' in fruit
Output: True
fruit='pineapple‘
‘papp' in fruit
71
8. Identity Operators
72
Example:
a = 25 a = 25
b = 25 b=a
a is b a is b
Output: True Output: True
# check id
print(id(a))
print(id(b))
The values are either a list of values separated by commas, a key=value list, or a combination of
both.
75
The Placeholders:
The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even
empty
placeholders {}.
#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)
76
PRACTICE
PROGRAMS
Program 2a: Write a program in Python to Read three
numbers and print their sum
num1 = int(input('Enter first number'))
num2 = int(input('Enter Second number'))
num3 = int(input('Enter Third Number'))
sum = num1 + num2 + num3
print('Sum=', sum)
Input: 23 34 45
Output: Sum=102
78
Program 2b: Write a program in Python to add two real numbers
and print their sum using format function
07/29/2024 79
num1 = float(input('enter first number'))
num2 = float(input('enter second number'))
t=a
a=b
b=t
82
# area of a triangle from its sides
import math
s = float(a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
84
Pgm No.6
Program 6: Write a program in Python to Roots
of a quadratic equation ax**2 + bx + c = 0 given
a,b and c
07/29/2024 85
import math
a = float(input('Enter a'))
b = float(input('Enter b'))
c = float(input('Enter c'))
dis = (b**2) - (4*a*c)
root1 = (-b+ math.sqrt(dis))/(2*a)
root2 = (-b-math.sqrt(dis))/(2*a)
print('Root 1 ', root1)
print('Root2 ', root2)
Pgm No.7
Program 7a: Write a program in Python to Generate a
random number between 0 and 9
import random
print(random.randint(0,9))
07/29/2024 87
Pgm No.7
Program 7b: Write a program in Python to convert a decimal
number to binary, octal and hexa
07/29/2024 88
Pgm 8
Program 8a: Write a program in Python to Read the radius of a circle and
find its area
Program 8b: Write a program in Python to Read the radius of a circle and
find its circumference
07/29/2024 89
Pgm 9.
Program 9: Write a program in Python to An object’s momentum is a product
of its mass and velocity. Write a Python script to accept an object’s mass (in
kilograms) and velocity (in metres per second) as inputs and output its
momentum.
mass = float(input("Enter the mass of the object (in kilograms): "))
velocity = float(input("Enter the velocity of the object (in meters per second): "))
momentum = mass * velocity
print("The momentum of the object is: {} kg*m/s".format(momentum))
07/29/2024 90
Pgm No. 10
Program 10: Write a program in Python to Read a four
digit binary number one digit at a time starting from the
rightmost digit and print its decimal value
07/29/2024 91
ones = int(input('enter the ones digit'))
sum = int(ones * (2 ** 0))
tens = int(input('enter the tens digit'))
sum = int(sum + tens *(2**1))
hund = int(input('enter the hundreds digit'))
sum = int(sum + hund *(2**2))
th = int(input('enter the thousands digit'))
sum = int(sum + th*(2**3))
print('sum = ', sum)
Control Structures
1. Programming language provides 3 fundamental forms of control
structures:
93
C. Iterative: Control statements that can execute a particular set of
statements in a loop and terminates based on the given conditions.
• while
• for
• else suite
• break
• continue
• pass
• assert
• return
94
Sequential Control Statements
a = 10
b=a
print(“ a = b ”)
95
Selective Control Statements
2. ‘if’ statement:
syntax:
if condition:
statements
Example:
num = 1
str = ‘Yes’
if num == 1: if str == ‘No’:
print(“one”) print(“No”)
print(“I’m in if block”)
print(“Demo Program”)
96
Selective Control Statements
Nested ‘if’ statement:
Example:
vehicle = 1
type = ‘car’
c = ‘BMW’
b = ‘Honda’
if vehicle:
if type == ‘car’:
if c == ‘BMW’:
print(“we have a vehicle and it’s a BMW car”)
if type == ‘bike’:
if b == ‘Honda’:
print(“we have a vehicle and it’s a Honda bike”)
97
Selective Control Statements
2. ‘if - else’ statement:
syntax:
if condition:
statements
else:
statements
Example:
vehicle = ‘car’
if vehicle == ‘bike’:
print(“Riding a bike”)
else
print(“Riding a car”)
98
Selective Control Statements
2. ‘if – elif - else’ statement:
syntax:
if condition:
statements
elif condition:
statements
else:
statements
Example: Assigning a letter grade based on a numerical score
G = int(input("Enter number: "))
if G >= 90 and G <= 100:
print("A")
elif G >= 80 and G < 90:
print("B")
elif G >= 70 and G < 80:
print("C")
elif G >= 60 and G < 70:
print("D")
elif G >= 0 and G < 60:
print("F")
else:
print("Please enter a valid grade between 0 and 100.") 99
Program - 11
Program 11a: Write a program in Python to Write a python program
to determine a number is even or odd.
100
Write a python program to determine a number is even or odd.
if x%2 == 0:
print(“Even number”)
else:
print(“Odd number”)
101
Program -11
Program 11b: Write a python program to know whether a number is
positive or negative or zero.
102
Write a python program to know whether an input number is positive,
negative or zero.
if x<0:
print(“Negative number”)
elif x>0:
print(“Positive number”)
else:
print(“Zero”)
103
Program - 12
104
Read two numbers num1 and num2 and find the largest of two.
105
Program 12b: Write a Program in Python to Read three
numbers and find the largest of three.
num1 = int(input(“Enter num1”))
num2 = int(input(“Enter num2”))
num3 = int(input(“Enter num3”))
106
Program - 13
Program 13a: Write a Python script that reads the numeric grade of a
student and print its equivalent letter grade as given below:
107
Example: Assigning a letter grade based on a numerical score
G = int(input("Enter number: "))
if G >= 90 and G <= 100:
print("A")
elif G >= 80 and G < 90:
print("B")
elif G >= 70 and G < 80:
print("C")
elif G >= 60 and G < 70:
print("D")
elif G >= 0 and G < 60:
print("F")
else:
print("Please enter a valid grade between 0 and 100.")
108
Program 13b
Read a character A or B or C.
If the character input is A, program should print ‘Apple’;
if character entered is B, program should print ‘Banana’
if character entered is C, program should print ‘Coconut’
If ch == ‘A’:
print(“Apple”)
elif ch == ‘B’:
print(“Banana”)
elif ch == ‘C’:
print(“Coconut”)
else:
print(“Invalid option”)
109
Program 14a: Write a Python script to read the length and breadth of a
rectangular garden in centimeters. The program should also find the cost of
fencing the garden, if the cost of fencing per cm Rs.168.
Program :
l = float(input("enter the length of the garden"))
b = float(input("enter the breadth of the garden"))
p = 2 * (l + b)
cost = p * 168
print('Perimeter of the garden is', p)
print('Cost of fencing the garden is', cost)
110
Program 14b: Write a Python script to read the name and age of
two persons x and y.
The program should also print the younger of the two.
Sample Input :
Name : David Age : 67
Name: Jennifer Age : 32
Output:
Jennifer is the youngest
111
Program:
name1 = input("Enter the name of first person")
age1 = int(input("Enter the age of first person"))
name2 = input("Enter the name of second person")
age2 = int(input("Enter the age of second person"))
if age1<age2:
print(name1, "is the youngest")
else:
print(name2, "is the youngest")
Program 15a: Write a Program to read the three sides of a triangle
and check whether it is Equilateral, Isosceles or Scalene Triangle
113
Program:
a = int(input("ENter the first side"))
b = int(input("ENter the second side"))
c = int(input("ENter the third side"))
115
Program:
c = input("Enter a character")
x = ord(c)
117
if (x > 0 and y > 0):
print ("lies in First quadrant")
119
While Loop
• Syntax
while condition:
suite (Statements within the same indentation belongs to the
same group called suite)
• Definite loop i=1
a program loop in which the number of times the loop will iterate can be while (i<6):
determined before the loop is executed. print(i)
i=i + 1
• Indefinite loop print('Good bye!')
program loop in which the number of times the loop will iterate cannot be
determined before the loop is executed.
120
• The break Statement: With the break statement we can stop the loop even if the while condition is true:
Example: i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Exit the loop when i is 3
The continue Statement: With the continue statement we can stop the current iteration, and continue with the next:
Example: Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement: With the else statement we can run a block of code once when the condition no longer is true:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
121
Program 17: Write a program using while loop and for loop in Python
that sums the first n integers, for a given (positive) value n entered by
the user.
# this program finds 1+2+3+…..+n, for a given n
sum = 0
current = 1
n = int(input("Enter a value:"))
while current <= n:
sum = sum + current
current = current + 1
print("Sum=", sum)
123
Find output
124
Looping Through a String: The for statement can be applied to all sequence types, including strings. Thus, iteration
over a string can be done as follows (which prints each letter on a separate line)
for x in “Hello":
print(x)
The break Statement: With the break statement we can stop the loop before it has looped through all the items:
Example: Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
The continue Statement: With the continue statement we can stop the current iteration of the loop, and continue with
the next. Example: Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
125
Range()
• Used to generate a sequence of numbers
• range(10) will generate numbers from 0 to 9 (10 numbers)
• Can define the start, stop and step size as range
• Default step size is 1
• All numbers generated are not stored in memory
• >>> range(10)
range(0, 10)
126
List()
• To display all the numbers generated by range()
• >>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2,8))
[2, 3, 4, 5, 6, 7]
>>> list(range(2,20,3))
[2, 5, 8, 11, 14, 17]
127
Using range() in for loop
• range() is also used in for loop to iterate over a sequence of
numbers
• Example
Program
n = int(input('Enter a number'))
for i in range(1,n+1):
print(i)
Enter a number 3
1
2
3
128
Program 18: Write a Python Program to read ‘n’ numbers and count positive,
negatives and zeros among them
np = 0
nn = 0
nz = 0
counter = 1
n = int(input('Enter the total no. of numbers'))
while counter <= n:
counter = counter + 1
num = int(input('Enter a number'))
129
if num < 0:
nn = nn + 1
elif num > 0:
np = np + 1
else:
nz = nz + 1
print('Positive count is {0}\n Negative count is {1}\n Zeros are
{2}'.format(np,nn,nz))
130
Program 19a:Write a program to check if the given number is prime or not
num=int(input())
if num==1 or num==0:
print ("Neither prime nor composite")
else:
for i in range(2,num):
if (num%i==0):
print("Not Prime")
break
else:
print("Prime")
131
Multiplication table of a given number.
Program 19b: Write a Python program that produces the multiplication
table for a specified number. The program should take the desired number
as input, and then output the multiplication table up to a certain limit,
such as up to 10.
n = int(input('Enter a number'))
for i in range(1,10+1):
print("{0} * {1} = {2}".format(n,i,n*i))
89
for i in range(n): # Loop from 0 to 4
*
**
for j in range(i): # Loop from 0 to i-1
Program 20: Write a Python program to construct the following pattern, using a nested for loop.
90
FUNCTIONS
• A function is a piece of code in a program. The function
performs a specific task.
The advantages of using functions are:
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding
1
3
Syntax of
Function
def function_name (parameters):
Therestatement(s)
are two basic types of functions.
Built-in functions and user defined ones.
The built-in functions are part of the Python language.
Examples are: min(),max(), len() or abs().
1
3
2. User Defined Functions
• A function defined by the user in a program is known as
user defined function.
• Any name can be given to a user defined function, except
python keywords.
• we define the user-defined function using def keyword,
followed by the function name.
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the function
name and parentheses ( ).
• Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
• The code block within every function starts with a colon : and is
indented.
• The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments is
the same as return None.
1
3
Ex.-1
def displayHello():
print(‘***********************’)
print(‘Hello World’)
print(‘**********************’)
1
4
PARMETERS AND ARGUMENTS IN FUNCTION
Parameters are used to give inputs to function. They are specified with a pair of parenthesis
in the functions definition.
Arguments are values actually passed to functions when it is calling it. It will appear in
function call.
#wrong. Find why
Ex-2 def my_func(x, y, z):
def my_func(x, y, z): a=x+y
a=x+y b=a*z
return b
b=a*z
print(my_func(10,20,30))
return b
print(my_func(10.3,20.4,30))
print(my_f
unc(10,20,
30))
print(my_f
unc(10.3,2
0.4,30))
1
4
Arguments
Arguments can be passed to functions following the order in which they appear
in the function definition.
Ex-3
def print_parameters(a,b,c,d):
print("1st param:", a)
print("2nd param:", b) Output
print("3rd param:", c) 1st param: A
print("4th param:", d) 2nd param: B
3rd param: C
print_parameters("A", "B", "C",
4th param: D
"D")
1
4
Specifying default
values
During the definition of a function it is possible to specify default values.
Ex-4
def print_parameters(a="defaultA", b="defaultB",c="defaultC"):
print("a:",a)
print("b:",b)
print("c:",c)
print_parameters("param_A")
O
u
t
# Try another example with integer/float values p
c: defaultC
u
t
a: param_A
b: defaultB
1
4
Defining and Calling Value-Returning Functions
and Functions returning multiple values
• A call to a value returning function is an expression
• value is returned using a return statement.
Ex:
def avg(n1,n2,n3):
return (n1+n2+n3)/3.0
#function call
result = avg(10,20,30)
print(result)
Positional, Keyword and default
Arguments in Python
• A positional argument is an argument that is
assigned to a particular parameter on its position
in the argument list as given below
• Example 1: Positional Arguments
• def mortgageRate(amount, rate, term)
• ……………………………………………………………
• >>>monthly_payment = mortagageRate(35000,
• 0.06, 20)
Keyword Argument
• A keyword argument is an argument that is
specified by parameter name. There is no space
before and after the equal sign in a keyword
argument.
• Example : Keyword Arguments
• def mortgageRate(amount, rate, term)
• ……………………………………………………………
• >>>monthly_payment = mortagageRate(rate=0.06,
term = 20, amount =35000)
• A default argument is an argument that can be
optionally provided in a given function call. The
parameter is assigned a default value if not
provided in the calling statement.
• Example 5 Default Arguments
• def mortgageRate(amount, rate, term = 20)
• ……………………………………………………………
• >>>monthly_payment = mortagageRate(35000,
0.06)
Program 22a: Write a Program in Python to Find the factorial
of a given number using a function
# function to find the factorial of a given number n
def fact(num):
if num==0 or num==1:
return(1)
else:
factorial=1
for i in range(1,num+1):
factorial=factorial*i
return factorial
num = int(input('Enter a number’))
print(f'Factorial of {num} is {fact(num)}')
148
Program 22b:Write a Python function that takes a list of temperatures
in a given week from Monday to Sunday and returns the highest and
lowest temperature in that week
def maxmintemp(temps):
return(max(temps), min(temps))
temps=[]
while True:
t = float(input('Enter a temperature: '))
if t > 0:
temps.append(t)
else:
break
print(temps)
highlow = maxmintemp(temps)
print('The highest Temperature is', highlow[0])
print('The lowest Temperature is', highlow[1])
10
Lambda function
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only have one
expression.
• Syntax of Lambda Function in pyhton lambda
arguments: expression
Example:
x = lambda a, b : a * b print(x(5, 6))
1
5
Thank You
151