0% found this document useful (0 votes)
6 views67 pages

Module 2 Functions 9-4-25

Uploaded by

asmashariff2330
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views67 pages

Module 2 Functions 9-4-25

Uploaded by

asmashariff2330
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Introduction to Python Programming–

BPLCK24205B

Module-2: Functions and Lists


Functions: def Statements with Parameters, Return Values and return
Statements, The
None Value, Keyword Arguments and print(), Local and Global Scope, The
global
Statement, Exception Handling, A short program : Guess the Number.

Lists: The List Data Type, Working with Lists, Augmented Assignment
Operators,
Methods, List-likeTypes: Strings and Tuples, References
FUNCTIONS
Functions
 A function is like a mini program within a program

 A major purpose of functions is to group code that gets executed


multiple times

 A program may have


• Built – in functions
• User defined functions
Built – in functions so far..
 print()

 input()

 len()
User-defined functions
• A function definition contains
Syntax

• def keyword
• Function name
• A colon
• An indented block of code

• Function names are case sensitive


Example of User defined
function

• 2 parts of a function

• Function definition

• Function call
Output
ARGUMENTS AND PARAMETERS
Arguments and Parameters

 Arguments are values passed in a function call

 Parameters are variables that contain arguments.

 The value stored in a parameter is forgotten when the function


returns.
Arguments and Parameters

Output
RETRUN VALUES AND RETURN
STATEMENTS
Return Values and return
Statements
 A function definition can contain a return statement

 A return statement specifies what value the function returns

 A return statement consists of the following:


• The return keyword
• The value or expression that the function should return

 The expression with a return statement evaluates to a return value


Return Values and return
Statements

Output Output
THE NONE VALUE
The None value
 None represents the absence of a value

 It belongs to NoneType data type

 It begins with an uppercase N

 Python adds return None to the end of any function definition with
no return statement

 If a return statement without a value is used, then None is returned


Example of NoneType

Output

Output
Keyword Arguments and the print() Function
Keyword Arguments and the print()
Function
 Keyword arguments are often used for optional
parameters.

 For example, the print() function has optional


parameters end and sep

 Specify what should be printed at the end of its


arguments and between its arguments (separating
them), respectively
Keyword Arguments and the print()
Function
Keyword Arguments and the print()
Function
 The print()function automatically adds a newline character to the
end of the string it is passed.

 The end keyword argument can be set to change the newline


character to a different string.

 When you pass multiple string values to print(), the function will
automatically separate them with a single space.

 But the default separating string can be replaced by passing the


sep keyword argument a different string.
Local and Global Scope
Local and Global Scope
 Parameters and variables that are assigned in a called function are
said to exist in that function’s local scope.

 Variables that are assigned outside all functions are said to exist in
the global scope.

 A variable that exists in a local scope is called a local variable

 A variable that exists in the global scope is called a global variable.

 A cannot be both local and global.


Local and Global Scope
 Code in the global scope, outside of all functions, cannot use any
local variables.

 Code in a local scope can access global variables.

 Code in a function’s local scope cannot use variables in any other


local scope.

 You can use the same name for different variables if they are in
different scopes.
Local Variables Cannot Be Used in the Global
Scope
Local Scopes Cannot Use Variables in Other Local
Scopes
Global Variables Can Be Read from a Local
Scope
Local and Global Variables with the Same
Name
The global statement
The global statement

 To modify a global variable


from within a function

 global statement is used


Rules for identifying local and global variables
 If a variable is being used in the global scope (that is, outside of all
functions), then it is always a global variable.

 If there is a global statement for that variable in a function, it is a


global variable.

 Otherwise, if the variable is used in an assignment statement in the


function, it is a local variable.

 But if the variable is not used in an assignment statement, it is a


global variable.
Rules for identifying local and global variables
Exception Handling
Python Exception

Common Exceptions
ZeroDivisionError: Occurs when a number is divided by zero.

NameError: It occurs when a name is not found. It may be local


or global.

IndentationError: If incorrect indentation is given.

IOError: It occurs when Input Output operation fails.

EOFError: It occurs when the end of the file is reached, and yet
operations are being performed
Exception Handling
An error, or exception, in your program means the entire program
will crash.

Errors can be handled with try and except statements

The code that could potentially have an error is put in a try clause.

The program execution moves to the start of a following except


clause if an error happens.

After running that code in except, the execution continues as


normal.
The problem without handling exceptions
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)

#other code: Output:


print("Hi I am other part of the
program") Enter a:12
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <modu
c = a/b;
ZeroDivisionError: division by zero
Exception handling in python
The try-expect statement
Example 1

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")

Output:

Enter a:30
Enter b:0
Can't divide with zero
The except statement with no
exception
Example

try: Enter a:10


a = int(input("Enter a:"))
b = int(input("Enter b:"))
Enter b:4
c = a/b; a/b = 2
print("a/b = %d"%c)
except: Hi I am else block
print("can't divide by zero")
else:
print("Hi I am else block")

Enter a:5
Enter b:0
can't divide by zero
Exception Handling

 An error, or exception, in
your program means the
entire program will crash.

 Errors can be handled with


try and except statements
Exception Handling

 The code that could


potentially have an error is
put in a try clause.

 The program execution


moves to the start of a
following except clause if an
error happens.

 After running that code in


except, the execution
continues as normal.
A Short Program: Guess the Number
Output: Run1 Output: Run2
POINTS TO PONDER 
FUNCTION LOCAL SCOPE
Contd ….
GLOBAL SCOPE NAMING VARIABLES
Contd ….
GLOBAL KEYWORD
Program to print Collatz
Sequence
More example programs on
functions
Example

Output:
2
4
Example of a recursive function

Output:
The factorial of 3
is 6
Using Global and Local variables in
the same code

Output:
global global
local
Global variable and Local variable
with same name

Output:
local x: 10
global x: 5
Introduction to Python Programming–
BPLCK24205B

Module-2: Functions and Lists


Functions: def Statements with Parameters, Return Values and return
Statements, The
None Value, Keyword Arguments and print(), Local and Global Scope, The
global
Statement, Exception Handling, A short program : Guess the Number.

Lists: The List Data Type, Working with Lists, Augmented Assignment
Operators,
Methods, List-likeTypes: Strings and Tuples, References
Check Even or Odd Number

print("Enter the Number: ")


num = int(input())
if num%2==0:
print("\n It is an Even Number")
else:
print("\n It is an Odd Number")

09/21/2025
52
Check Alphabet or Not

print("Enter a Character: ")


c = input()
if c>='a' and c<='z':
print("\n It is an alphabet")
elif c>='A' and c<=‘Z':
print("\n It is an alphabet")
else:
print("\n It is not an alphabet")
Check Vowel or Consonant using if-elif-else

print("Enter the Character: ")


c = input()
if c=='a' or c=='e' or c=='i' or c=='o' or c=='u':
print("\n It is a Vowel“)
elif c=='A' or c=='E' or c=='I' or c=='O' or c=='U':
print("\n It is a Vowel“)
else:
print("\n It is a Consonant")

09/21/2025
54
Check Leap Year

print("Enter the Year: ")


y = int(input())
if y%4==0 :
print("\n It is a Leap Year")
else:
print("\n It is not a Leap Year")

09/21/2025
55
Find Area of Square To add two numbers

print("Enter the Side Length of Square: ") print("Enter First Number: ")
len = float(input()) numOne = int(input())
a = len*len print("Enter Second Number: ")
print("\nArea = ", a) numTwo = int(input())
res = numOne + numTwo
print("\nResult = ", res)

09/21/2025
56
To add, sub, multiply and divide two numbers

print("Enter First Number: ")


numOne = int(input())
print("Enter Second Number: ")
numTwo = int(input())
res = numOne+numTwo
print("\nAddition Result = ", res)
res = numOne-numTwo
print("Subtraction Result = ", res)
res = numOne*numTwo
print("Multiplication Result = ", res)
res = numOne/numTwo
print("Division Result = ", res)
Python Program to Calculate Average and Percentage
Marks

print("Enter Marks Obtained in 5 Subjects: ")


mOne = int(input())
mTwo = int(input())
mThree = int(input())
mFour = int(input())
mFive = int(input())
sum = mOne+mTwo+mThree+mFour+mFive
avg = sum/5
perc = (sum/500)*100
print("Average Mark = “, avg)
print("Percentage Mark = “, perc) 09/21/2025
58
Find Area of Rectangle
print("Enter Length of Rectangle: ")
len = float(input())
print("Enter Breadth of Rectangle: ")
b = float(input())
a = len*b
print("\nArea = ", a)

Find Area of Triangle based on Base and Height

print("Enter the Base Length of Triangle: ")


b = float(input())
print("Enter the Height Length Triangle: ")
h = float(input())
a = 0.5 * b * h
09/21/2025
print("\nArea = ", a) 59
Find Area of Circle

print("Enter the Radius of Circle: ")


r = float(input())
a = 3.14*r*r
print("\nArea = ", a)

Concatenate Two Strings using +


print("Enter the First String: ")
strOne = input()
print("Enter the Second String: ")
strTwo = input()
strThree = strOne + strTwo
print("\nConcatenated String:” + strThree)
09/21/2025
60
Calculator Program in Python using function
def addition(n1, n2):
if operation == 1:
return n1 + n2
print (n1, "+", n2, "=", addition(n1, n2))
def subtraction(n1, n2):
elif operation == 2:
return n1 - n2
print (n1, "-", n2, "=", subtraction(n1, n2))
def multiplication(n1, n2):
elif operation == 3:
return n1 * n2
print (n1, "*", n2, "=", multiplication(n1,
n2))
def division(n1, n2):
return n1 / n2
elif operation == 4:
print("Select Operations") print (n1, "/", n2, "=", division(n1, n2))
print(
"1. Addition\n" else:
"2. Subtraction\n" print("Invalid Input")
"3. Multiplication\n"
"4. Division\n")

operation = int(input("Enter choice of operation 1/2/3/4: "))

n1 = float(input("Enter the First Number: "))


n2 = float(input("Enter the Second Number: "))
Write a Python function to take an integer as an argument
and return the day of the week using elif statement.

def get_day_of_week(day_number):
if day_number == 1:
return "Monday"
elif day_number == 2:
return "Tuesday"
elif day_number == 3:
return "Wednesday"
elif day_number == 4:
return "Thursday"
elif day_number == 5:
return "Friday"
elif day_number == 6:
return "Saturday"
elif day_number == 7:
return "Sunday"
else:
return "Invalid day number"

day_number = int(input("Enter a number (1-7) representing the day of the


week: "))
print("Day of the week:", get_day_of_week(day_number))
Write a Python function to return the
smallest of two numbers.

def smallest_of_two(num1, num2):


if num1 < num2:
return num1
else:
return num2

a = int(input("Enter the number1\n"))


b = int(input("Enter the number2\n"))
c=smallest_of_two(a,b)
print("The smallest number between", a, "and", b,
"is:", c)
4. Write a function called check-season, it takes a month
parameter and returns the season: Autumn, Winter, Spring
or Summer.

def check_season(month):
if month == 2 or month==3:
return "Spring"
elif month == 4 or month== 5 or month==6:
return "Summer"
elif month == 7 or month ==8 or month==9 or month ==
10:
return "Autumn"
elif month ==11 or month == 12 or month==1:
return "Winter"
else:
return "Invalid month"
month = int(input("Enter the month (as a number): "))
print("Season:", check_season(month))
def simple_calculator(operation):
if operation == 1:
print("Addition")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 + num2
elif operation == 2:
print("Subtraction")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 - num2
elif operation == 3:
print("Multiplication")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 * num2
elif operation == 4:
print("Division")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 / num2
else:
print("Invalid operation.")
return None
print("Result:", result)
return result

# Example usage:
operation = int(input("Enter the operation (1: Addition, 2: Subtraction, 3:
Multiplication, 4: Division): "))
simple_calculator(operation)
09/21/2025 67

You might also like