Python Functions#
In this class, youâll learn about functions, what a function is, the syntax, components, and types of functions. Also, youâll learn to create a function in Python.
What is a function in Python?#
In Python, a function is a block of organized, reusable (DRY- Donât Repeat Yourself) code with a name that is used to perform a single, specific task. It can take arguments and returns the value.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it improves efficiency and reduces errors because of the reusability of a code.
Types of Functions#
Python support two types of functions
[Built-in]function
[User-defined] function
1.Built-in function
The functions which are come along with Python itself are called a built-in function or predefined function. Some of them are:
range()
, print()
, input()
, type()
, id()
, eval()
etc.
Example: Python range()
function generates the immutable sequence of numbers starting from the given start integer to the stop integer.
>>> for i in range(1, 10):
>>> print(i, end=' ')
1 2 3 4 5 6 7 8 9
User-defined function
Functions which are created by programmer explicitly according to the requirement are called a user-defined function.
Syntax:
def function_name(parameter1, parameter2):
"""docstring"""
# function body
# write some action
return value
Defining a Function#
def
is a keyword that marks the start of the function header.function_name
to uniquely identify the function. Function naming follows the sameparameter
is the value passed to the function. They are optional.:
(colon) to mark the end of the function header.function body
is a block of code that performs some task and all the statements infunction body
must have the same indentation level (usually 4 spaces).âââdocstringâââ documentation string is used to describe what the function does.
return
is a keyword to return a value from the function.. A return statement with no arguments is the same as returnNone
.
Note: While defining a function, we use two keywords,
def
(mandatory) andreturn
(optional).
Example:
>>> def add(num1,num2): # Function name: 'add', Parameters: 'num1', 'num2'
>>> print("Number 1: ", num1) # Function body
>>> print("Number 2: ", num2) # Function body
>>> addition = num1 + num2 # Function body
>>> return addition # return value
>>> res = add(2, 4) # Function call
>>> print("Result: ", res)
Defining a function without any parameters#
Function can be declared without parameters.
# Example: Define and call a greeting function.
# Define a function named 'greet' to print a welcome message
def greet():
print("Welcome to Python for Artificial Intelligence")
# Call the 'greet' function
greet()
Welcome to Python for Artificial Intelligence
# Example: Define and call a function to add two numbers.
# Define a function named 'add_two_numbers'
def add_two_numbers():
# Assign values to two numbers
num_one = 8
num_two = 14
# Calculate the total by adding the two numbers
total = num_one + num_two
# Print the result
print(total)
# Call the 'add_two_numbers' function
add_two_numbers()
22
Defining a function without parameters and return
value#
Function can also return values, if a function does not have a return
statement, the value of the function is None. Let us rewrite the above functions using return
. From now on, we get a value from a function when we call the function and print it.
# Example: Define and call a function to add two numbers.
# Define a function named 'add_two_numbers'
def add_two_numbers():
# Assign values to two numbers
first_number = 3
second_number = 6
# Calculate the total by adding the two numbers
sum_total = first_number + second_number
# Return the total
return sum_total
# # Print the result of calling the 'add_two_numbers' function
print(add_two_numbers())
9
# Example: Define and call a function to generate a full name.
# Define a function named 'generate_full_name'
def generate_full_name():
# Assign values to the first and last names
first_name = 'Fahad'
last_name = 'Ali'
# Create a variable for the space between first and last names
space = ' '
# Concatenate the first and last names to form the full name
full_name = first_name + space + last_name
# Return the full name
return full_name
# Print the result of calling the 'generate_full_name' function
Answer = generate_full_name()
print(Answer)
Fahad Ali
Defining a function with parameters#
In a function we can pass different data types(number, string, boolean, list, tuple, dictionary or set) as a parameter.
Single Parameter:#
If our function takes a parameter we should call our function with an argument
# Example: Greeting
def greet(person_name):
"""
This function greets the person passed in as a parameter
"""
print("Hello, " + person_name + ". Good morning!") # No output!
# # Call the 'greet' function with a specific argument
greet('Ali')
Hello, Ali. Good morning!
# Example: Calculate the sum of numbers up to the specified limit
def sum_of_numbers_up_to_n(limit):
"""
This function calculates the sum of numbers up to the specified limit (inclusive)
"""
total_sum = 0
# Iterate through numbers from 0 to 'limit' and add them to the total
for i in range(limit + 1):
total_sum += i
# Print the calculated sum
print(total_sum)
# Calculate and print the sum for different limits
sum_of_numbers_up_to_n(10) # Expected output: 55
sum_of_numbers_up_to_n(150) # Expected output: 5050
55
11325
Two Parameter:#
A function may or may not have a parameter or parameters. A function may also have two or more parameters. If our function takes parameters we should call it with arguments.
# Example: Welcome message for a Python Data Science course participant
def welcome_participant(student_name, course_title):
"""
This function generates a welcome message for a participant in a Python Data Science course.
"""
print("Hello", student_name + ", Welcome to Python for Artificial Intelligence!")
print("Your course name is", course_title)
# Call the 'welcome_participant' function with specific arguments
welcome_participant('Ali', 'Lahore School of Management') # Output the welcome message
Hello Ali, Welcome to Python for Artificial Intelligence!
Your course name is Lahore School of Management
Defining a function with parameters and return
value#
# Example: Greeting Message Generator
def generate_greeting_message(name):
"""
This function generates a personalized greeting message for a person.
"""
greeting_message = name + ', welcome to Artificial Intelligence'
return greeting_message
# Call the 'generate_greeting_message' function with a specific argument
print(generate_greeting_message('Fahad'))
Fahad, welcome to Artificial Intelligence
# Example: Square of a Number Calculator
def calculate_square(x):
"""
This function calculates the square of a given number.
"""
square_result = x * x
return square_result
# Call the 'calculate_square' function with a specific argument
print(calculate_square(15))
225
# Example: Age Calculator
def calculate_age(current_year, birth_year):
"""
This function calculates the age based on the current year and birth year.
"""
person_age = current_year - birth_year
return person_age
# Call the 'calculate_age' function with specific arguments
print('Age: ', calculate_age(2024, 1997))
Age: 27
Function return
Statement#
In Python, to return value from the function, a return
statement is used. It returns the value of the expression following the returns keyword.
Syntax:
def fun():
statement-1
statement-2
statement-3
.
.
return [expression]
The return
value is nothing but a outcome of function.
The
return
statement ends the function execution.For a function, it is not mandatory to return a value.
If a
return
statement is used without any expression, then theNone
is returned.The
return
statement should be inside of the function block.
Return Single Value#
print(greet("Fahad"))
Hello, Fahad. Good morning!
None
Return Multiple Values#
You can also return multiple values from a function. Use the return statement by separating each expression by a comma.
# Example 1: Arithmetic Operations Calculator
def perform_arithmetic_operations(num1, num2):
"""
This function performs addition, subtraction, multiplication, and division on two numbers.
"""
addition_result = num1 + num2
subtraction_result = num1 - num2
multiplication_result = num1 * num2
division_result = num1 / num2
# Return four values representing the results of the arithmetic operations
return addition_result, subtraction_result, multiplication_result, division_result
# Call the 'perform_arithmetic_operations' function with specific arguments
addition, subtraction, multiplication, division = perform_arithmetic_operations(58,54)
# Display the results
print("Addition: ", addition)
print("Subtraction: ", subtraction)
print("Multiplication: ", multiplication)
print("Division: ", division)
Addition: 112
Subtraction: 4
Multiplication: 3132
Division: 1.0740740740740742
Return Boolean Values#
# Example: Check if a Number is Even
def is_even(number):
"""
This function checks if a given number is even.
"""
if number % 2 == 0:
print('Even')
return False
else:
print('Odd')
return True
# Check and print the results for different numbers
print(is_even(10)) # Expected output: True
print(is_even(7)) # Expected output: False
Even
False
Odd
True
Letâs create a function(with docstring)#
def is_even(num):
"""
This function returns if a given number is odd or even
input - any valid integer
output - odd/even
created on - 16th Nov 2022
"""
if type(num) == int:
if num % 2 == 0:
return 'even'
else:
return 'odd'
else:
return 'pagal hai kya?'
# function
# function_name(input)
for i in range(1,11):
x = is_even(i)
print(x)
odd
even
odd
even
odd
even
odd
even
odd
even
print(is_even.__doc__)
This function returns if a given number is odd or even
input - any valid integer
output - odd/even
created on - 16th Nov 2022
2 Point of views#
is_even('hello')
'pagal hai kya?'
Parameters Vs Arguments#
Types of Arguments#
Default Argument
Positional Argument
Keyword Argument
def power(a=1,b=1):
return a**b
power()
1
# positional argument
power(2,3)
8
# keyword argument
power(b=3,a=2)
8
*args and **kwargs
#
*args and **kwargs
are special Python keywords that are used to pass the variable length of arguments to a function
def multiply(a,b):
return a*b
multiply(2,3)
6
# *args
# allows us to pass a variable number of non-keyword arguments to a function.
def multiply(*args):
product = 1
for i in args:
product = product * i
print(args)
return product
multiply(1,2,3,4,5,6,7,8,9,10,12)
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12)
43545600
# *args
# allows us to pass a variable number of non-keyword arguments to a function.
def multiply(*kwargs):
product = 1
for i in kwargs:
product = product * i
print(kwargs)
return product
multiply(1,2,3,4,5,6,7,8,9,10,12)
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12)
43545600
# **kwargs
# **kwargs allows us to pass any number of keyword arguments.
# Keyword arguments mean that they contain a key-value pair, like a Python dictionary.
def display(**kwargs):
for (key,value) in kwargs.items():
print(key,'->',value)
display(pakistan='islamabad', india='delhi',srilanka='colombo',nepal='kathmandu')
pakistan -> islamabad
india -> delhi
srilanka -> colombo
nepal -> kathmandu
def display(**ali):
for (key,value) in ali.items():
print(key,'->',value)
display(pakistan='islamabad', india='delhi',srilanka='colombo')
pakistan -> islamabad
india -> delhi
srilanka -> colombo
Points to remember while using *args and **kwargs
#
order of the arguments matter(normal ->
*args
->**kwargs
)The words âargsâ and âkwargsâ are only a convention, you can use any name of your choice
How Functions are executed in memory?#
Without return statement#
L = [1,2,3]
print(L.append(4))
print(L)
None
[1, 2, 3, 4]
Variable Scope#
Difference between local and global variable#
Local Variable: A variable is defined inside a function and can only be used inside that function. It gets destroyed once the function execution is completed.
Global Variable: A variable is defined outside a function and can be used inside and outside the function.
def g(y):
print(x)
print(x+1)
x = 5
g(x)
print(x)
5
6
5
def f(y):
x = 1
x += 1
print(x)
x = 5
f(x)
print(x)
2
5
def h(y):
x += 1
x = 5
h(x)
print(x)
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Cell In[32], line 4
2 x += 1
3 x = 5
----> 4 h(x)
5 print(x)
Cell In[32], line 2, in h(y)
1 def h(y):
----> 2 x += 1
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
Nested Functions#
def f():
def g():
print('inside function g')
g()
print('inside function f')
f()
def f():
def g():
print('inside function g')
f()
g()
print('inside function f')
f()
def g(x):
def h():
x = 'abc'
x = x + 1
print('in g(x): x =', x)
h()
return x
x = 3
z = g(x)
def g(x):
def h(x):
x = x+1
print("in h(x): x = ", x)
x = x + 1
print('in g(x): x = ', x)
h(x)
return x
x = 3
z = g(x)
print('in main program scope: x = ', x)
print('in main program scope: z = ', z)
Functions are 1st class citizens#
# type and id
def square(num):
return num**2
type(square)
id(square)
2376899900128
# reassign
x = square
id(x)
x(3)
9
a = 2
b = a
b
2
# deleting a function
del square
square(3)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[37], line 1
----> 1 square(3)
NameError: name 'square' is not defined
# storing
L = [1,2,3,4,square]
L[-1](3)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[38], line 2
1 # storing
----> 2 L = [1,2,3,4,square]
3 L[-1](3)
NameError: name 'square' is not defined
s = {square}
s
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[39], line 1
----> 1 s = {square}
2 s
NameError: name 'square' is not defined
Returning a function#
def f():
def x(a, b):
return a*b
return x
val = f()(8,9)
print(val)
72
function as argument#
def func_a():
print('inside func_a')
def func_b(z):
print('inside func_c')
return z()
print(func_b(func_a))
inside func_c
inside func_a
None
Benefits of using a Function#
Code Modularity
Code Readibility
Code Reusability
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.
# x -> x^2
lambda x:x**2
# x(5)
<function __main__.<lambda>(x)>
# x,y -> x+y
a = lambda x,y:x+y
a(5,2)
7
Diff between lambda vs Normal Function#
No name
lambda has no return value(infact,returns a function)
lambda is written in 1 line
not reusable
Then why use lambda functions?
They are used with HOF(Higher Order Function)
# check if a string has 'a'
a = lambda s:'a' in s
a('hello')
False
# odd or even
a = lambda x:'even' if x%2 == 0 else 'odd'
a(6)
'even'
Higher Order Functions#
# Example
def square(x):
return x**2
def cube(x):
return x**3
# HOF
def transform(f,L):
output = []
for i in L:
output.append(f(i))
print(output)
L = [1,2,3,4,5]
transform(lambda x:x**3,L)
[1, 8, 27, 64, 125]
Map#
# square the items of a list
list(map(lambda x:x**4,[1,2,3,4,5]))
[1, 16, 81, 256, 625]
# odd/even labelling of list items
L = [1,2,3,4,5]
list(map(lambda x:'even' if x%2 == 0 else 'odd',L))
['odd', 'even', 'odd', 'even', 'odd']
# fetch names from a list of dict
users = [
{
'name':'Ali',
'age':45,
'gender':'male'
},
{
'name':'Asad',
'age':33,
'gender':'male'
},
{
'name':'Hina',
'age':50,
'gender':'female'
}
]
list(map(lambda users:users['age'],users))
[45, 33, 50]
Filter#
# numbers greater than 5
L = [3,4,5,6,7]
list(filter(lambda x:x>5,L))
[6, 7]
# fetch fruits starting with 'a'
fruits = ['apple','guava','cherry']
list(filter(lambda x:x.startswith('g'),fruits))
['guava']
Reduce#
# sum of all item
import functools
functools.reduce(lambda x,y:x+y,[1,2,3,4,5])
15
# find min
functools.reduce(lambda x,y:x if x>y else y,[23,11,45,10,1])
45
File Handling#
Some Theory#
Types of data used for I/O:#
Text - â12345â as a sequence of unicode chars
Binary - 12345 as a sequence of bytes of its binary equivalent
Hence there are 2 file types to deal with#
Text files - All program files are text files
Binary Files - Images,music,video,exe files
How File I/O is done in most programming languages#
Open a file
Read/Write data
Close the file
Writing to a file#
# case 1 - if the file is not present
f = open('sample.txt','w')
f.write('Hello world')
f.close()
# # since file is closed hence this will not work
f.write('hello')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[101], line 6
4 f.close()
5 # # since file is closed hence this will not work
----> 6 f.write('hello')
ValueError: I/O operation on closed file.
# write multiline strings
f = open('sample1.txt','w')
f.write('hello world')
f.write('\nhow are you?')
f.write('\nI am fine')
f.close()
# case 2 - if the file is already present
f = open('sample.txt','w')
f.write('Fahad Ali')
f.close()
how exactly open() works?#
# Problem with w mode
# introducing append mode
f = open('sample1.txt','a')
f.write('\nI am fine')
f.close()
# write lines
L = ['hello\n','hi\n','how are you\n','I am fine']
f = open('sample.txt','w')
f.writelines(L)
f.close()
L = ['hello\n','hi\n','how are you\n','I am fine']
f = open('./new/sample.txt','w')
f.writelines(L)
f.close()
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[106], line 3
1 L = ['hello\n','hi\n','how are you\n','I am fine']
----> 3 f = open('./new/sample.txt','w')
4 f.writelines(L)
5 f.close()
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\IPython\core\interactiveshell.py:343, in _modified_open(file, *args, **kwargs)
336 if file in {0, 1, 2}:
337 raise ValueError(
338 f"IPython won't let you open fd={file} by default "
339 "as it is likely to crash IPython. If you know what you are doing, "
340 "you can use builtins' open."
341 )
--> 343 return io_open(file, *args, **kwargs)
FileNotFoundError: [Errno 2] No such file or directory: './new/sample.txt'
# reading from files
# -> using read()
f = open('sample1.txt','r')
s = f.read()
print(s)
f.close()
hello world
how are you?
I am fine
I am fine
# reading upto n chars
f = open('sample1.txt','r')
s = f.read(20)
print(s)
f.close()
hello world
how are
# readline() -> to read line by line
f = open('sample1.txt','r')
print(f.readline(),end='')
print(f.readline(),end='')
f.close()
hello world
how are you?
# reading entire using readline
f = open('sample1.txt','r')
while True:
data = f.readline()
if data == '':
break
else:
print(data,end='')
f.close()
hello world
how are you?
I am fine
I am fine
line_number = 2 # Specify the line number you want to read
current_line = 0
with open('sample1.txt', 'r') as f:
while current_line < line_number:
data = f.readline()
current_line += 1
if data == '':
print("Specified line does not exist in the file.")
break
elif current_line == line_number:
print("Line", line_number, ":", data, end='')
f.close()
Line 2 : how are you?
Using Context Manager (With)#
Itâs a good idea to close a file after usage as it will free up the resources
If we dont close it, garbage collector would close it
with keyword closes the file as soon as the usage is over
# with
with open('sample.txt','w') as f:
f.write('Fahad Ali')
f.write('hello')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[113], line 1
----> 1 f.write('hello')
ValueError: I/O operation on closed file.
# try f.read() now
with open('sample1.txt','r') as f:
print(f.read())
hello world
how are you?
I am fine
I am fine
# try f.readline() now
with open('sample1.txt','r') as f:
print(f.readline())
hello world
line_number = 2 # Specify the line number you want to read
current_line = 0
with open('sample1.txt', 'r') as f:
while current_line < line_number:
data = f.readline()
current_line += 1
if data == '':
print("Specified line does not exist in the file.")
break
if current_line == line_number:
print("Line", line_number, ":", data, end='')
Line 2 : how are you?
# moving within a file -> 10 char then 10 char
with open('sample1.txt','r') as f:
print(f.read(10))
print(f.read(10))
print(f.read(10))
print(f.read(10))
hello worl
d
how are
you?
I am
fine
I am
# benefit? -> to load a big file in memory
big_L = ['hello world ' for i in range(1000)]
with open('big.txt','w') as f:
f.writelines(big_L)
with open('big.txt','r') as f:
chunk_size = 20
while len(f.read(chunk_size)) > 0:
print(f.read(chunk_size),end='/')
f.read(chunk_size)
rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/rld hello world hell/
with open('sample1.txt','r') as f:
print(f.read(10))
print(f.tell())
hello worl
10
with open('sample1.txt','r') as f:
print(f.read(10))
print(f.tell())
f.seek(0)
print(f.read(10))
print(f.tell())
hello worl
10
hello worl
10
# seek and tell function
with open('sample1.txt','r') as f:
f.seek(15)
print(f.read(10))
print(f.tell())
print(f.read(10))
print(f.tell())
w are you?
25
I am fine
36
# seek during write
with open('sample.txt','w') as f:
f.write('Hello')
f.seek(2)
f.write('Yellow')
Problems with working in text mode#
canât work with binary files like images
not good for other data types like int/float/list/tuples
# working with binary file
with open('difference.jpeg','r') as f:
f.read()
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[76], line 2
1 # working with binary file
----> 2 with open('difference.jpeg','r') as f:
3 f.read()
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\IPython\core\interactiveshell.py:343, in _modified_open(file, *args, **kwargs)
336 if file in {0, 1, 2}:
337 raise ValueError(
338 f"IPython won't let you open fd={file} by default "
339 "as it is likely to crash IPython. If you know what you are doing, "
340 "you can use builtins' open."
341 )
--> 343 return io_open(file, *args, **kwargs)
FileNotFoundError: [Errno 2] No such file or directory: 'difference.jpeg'
# working with binary file
with open('difference.jpeg','rb') as f:
with open('screenshot.png','wb') as wf:
wf.write(f.read())
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[77], line 2
1 # working with binary file
----> 2 with open('difference.jpeg','rb') as f:
3 with open('screenshot.png','wb') as wf:
4 wf.write(f.read())
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\IPython\core\interactiveshell.py:343, in _modified_open(file, *args, **kwargs)
336 if file in {0, 1, 2}:
337 raise ValueError(
338 f"IPython won't let you open fd={file} by default "
339 "as it is likely to crash IPython. If you know what you are doing, "
340 "you can use builtins' open."
341 )
--> 343 return io_open(file, *args, **kwargs)
FileNotFoundError: [Errno 2] No such file or directory: 'difference.jpeg'
# working with other data types
with open('sample.txt','w') as f:
f.write(5)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[78], line 3
1 # working with other data types
2 with open('sample.txt','w') as f:
----> 3 f.write(5)
TypeError: write() argument must be str, not int
with open('sample.txt','w') as f:
f.write('5')
with open('sample.txt','r') as f:
print(int(f.read()) + 5)
10
# more complex data
d = {
'name':'Fahad',
'age':28,
'gender':'male'
}
with open('sample.txt','w') as f:
f.write(str(d))
with open('sample.txt','r') as f:
print((f.read()))
print(type(f.read()))
{'name': 'Fahad', 'age': 28, 'gender': 'male'}
<class 'str'>
Exception Handling#
There are 2 stages where error may happen in a program#
During compilation -> Syntax Error
During execution -> Exceptions
Syntax Error#
Something in the program is not written according to the program grammar.
Error is raised by the interpreter/compiler
You can solve it by rectifying the program
# Examples of syntax error
print 'hello world'
Cell In[83], line 2
print 'hello world'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
Other examples of syntax error#
Leaving symbols like colon,brackets
Misspelling a keyword
Incorrect indentation
empty if/else/loops/class/functions
a = 5
if a==3
print('hello')
Cell In[84], line 2
if a==3
^
SyntaxError: expected ':'
a = 5
if a==3:
print('hello')
Cell In[85], line 3
print('hello')
^
IndentationError: expected an indented block after 'if' statement on line 2
# IndexError
# The IndexError is thrown when trying to access an item at an invalid index.
L = [1,2,3]
L[100]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[86], line 4
1 # IndexError
2 # The IndexError is thrown when trying to access an item at an invalid index.
3 L = [1,2,3]
----> 4 L[100]
IndexError: list index out of range
# ModuleNotFoundError
# The ModuleNotFoundError is thrown when a module could not be found.
import mathi
math.floor(5.3)
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[87], line 3
1 # ModuleNotFoundError
2 # The ModuleNotFoundError is thrown when a module could not be found.
----> 3 import mathi
4 math.floor(5.3)
ModuleNotFoundError: No module named 'mathi'
# KeyError
# The KeyError is thrown when a key is not found
d = {'name':'Fahad'}
d['age']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[88], line 5
1 # KeyError
2 # The KeyError is thrown when a key is not found
4 d = {'name':'Fahad'}
----> 5 d['age']
KeyError: 'age'
# TypeError
# The TypeError is thrown when an operation or function is applied to an object of an inappropriate type.
1 + 'a'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[89], line 3
1 # TypeError
2 # The TypeError is thrown when an operation or function is applied to an object of an inappropriate type.
----> 3 1 + 'a'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
# ValueError
# The ValueError is thrown when a function's argument is of an inappropriate type.
int('a')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[90], line 3
1 # ValueError
2 # The ValueError is thrown when a function's argument is of an inappropriate type.
----> 3 int('a')
ValueError: invalid literal for int() with base 10: 'a'
# NameError
# The NameError is thrown when an object could not be found.
print(k)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[91], line 3
1 # NameError
2 # The NameError is thrown when an object could not be found.
----> 3 print(k)
NameError: name 'k' is not defined
# AttributeError
L = [1,2,3]
L.upper()
# Stacktrace
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[92], line 3
1 # AttributeError
2 L = [1,2,3]
----> 3 L.upper()
5 # Stacktrace
AttributeError: 'list' object has no attribute 'upper'
Exceptions#
If things go wrong during the execution of the program(runtime). It generally happens when something unforeseen has happened.
Exceptions are raised by python runtime
You have to takle is on the fly
Examples#
Memory overflow
Divide by 0 -> logical error
Database error
# Why is it important to handle exceptions
# how to handle exceptions
# -> Try except block
# let's create a file
with open('sample.txt','w') as f:
f.write('hello world')
# try except demo
try:
with open('sample2.txt','r') as f:
print(f.read())
except:
print('sorry file not found')
sorry file not found
# catching specific exception
try:
# m=5
f = open('sample.txt','r')
print(f.read())
# print(m)
# print(5/0)
# print(5/2)
L = [1,2,3]
L[100]
except FileNotFoundError:
print('file not found')
except NameError:
print('variable not defined')
except ZeroDivisionError:
print("can't divide by 0")
except Exception as e:
print(e)
hello world
list index out of range
# else
try:
f = open('sample1.txt','r')
except FileNotFoundError:
print('file nai mili')
except Exception:
print('kuch to masla hai')
else:
print(f.read())
hello world
how are you?
I am fine
I am fine
# finally
# else
try:
f = open('sample2.txt','r')
except FileNotFoundError:
print('file nai mili')
except Exception:
print('kuch to masla hai')
else:
print(f.read())
finally:
print('ye to print hona hi tha')
file nai mili
ye to print hona hi tha
# raise Exception
# In Python programming, exceptions are raised when errors occur at runtime.
# We can also manually raise exceptions using the raise keyword.
# We can optionally pass values to the exception to clarify why that exception was raised
raise AttributeError('Aisy try na karo')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[100], line 1
----> 1 raise AttributeError('Aisy try na karo')
AttributeError: Aisy try na karo