12/9/23, 11:09 AM Python unit 4 programs.
ipynb - Colaboratory
#builtin functions print, len, sum, input, int, type
l = [11, 22, 33]
s = sum(l)
print(s)
n = len(l)
print(n)
s = "hello"
t = [Link]()
print(t)
a = 3.14
b = int(a)
print(type(a))
66
3
HELLO
<class 'float'>
#function creation using def keyword
def say_hello(): # function definition
print("hello")
say_hello() # calling function
hello
def greet():
name = input("enter you name : ")
print("hello " + name)
greet()
enter you name : John
hello John
#create a function to display this pattern
# *
# ***
# *****
def draw():
for i in range(1,7,2):
s="*"
print(f"{s*i:^7}")
draw()
*
***
*****
def draw():
n = int(input("enter n : "))
for i in range(1,n,2):
s="*"
print(f"{s*i:^{n}}")
draw()
enter n : 7
*
***
*****
[Link] 1/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
#function passing parameters
def multiplication(a, b): # parameters
print("result : ")
print(a * b)
multiplication(2, 3) # arguments
result :
6
#find the output
def fun(a, b, name):
print(f"name = {name}")
print(f"score = {a + b}")
fun(10, 20, "John")
name = John
score = 30
#find sum of squares of given two numbers
def square_sum(a, b):
print((a**2) + (b**2))
square_sum(2, 4)
20
#calculate mileage of cars in given list of dictionary
cars = [
{"make":"honda", "model":"city", "km":200,"fuel":10},
{"make":"ford", "model":"fiesta", "km":200,"fuel":20},
{"make":"kia", "model":"seltos", "km":200,"fuel":30},
]
def find_mileage(car):
name = f"{car['make']} {car['model']}"
mileage = car["km"] / car["fuel"]
print(f"{name} does {mileage} km/litre")
for c in cars:
find_mileage(c)
honda city does 20.0 km/litre
ford fiesta does 10.0 km/litre
kia seltos does 6.666666666666667 km/litre
#function return values
def total(a, b, c, d):
c = a + b + c + d
return c
res = total(10, 20, 30, 40)
print(f"total = {res}")
avg = total(20, 30, 40, 70) / 4
print(f"average = {avg}")
total = 100
average = 40.0
#factorial of a number
def factorial(n):
res = 1
for i in range(1, n+1):
res = res * i
return res
print(factorial(5))
rs = factorial(3)
print(rs)
[Link] 2/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
120
6
def add_two_values(a, b):
c = a + b
return c
s = add_two_values(10, 20)
print(s)
30
def remainder(a, b):
return a % b
r = remainder(5, 3)
print(r)
#divide two numbers and return quotient if denominator is not 0 else return warning message
def divide(x, y):
if y == 0:
return "You tried to divide by zero!"
else:
return x / y
print(divide(10, 2))
print(divide(6, 0))
5.0
You tried to divide by zero!
#function returning list
def double_list(l):
j = []
for i in l:
[Link](i*2)
return j
r = double_list([10, 20, 30])
print(r)
[20, 40, 60]
#return dictionary by updating values in upper case
def update_dictionary(td):
new_d = {}
for i in td:
new_d[i] = td[i].upper()
return new_d
n_d = update_dictionary({"IN":"india", "US":"united states", "JP":"japan", "SG":"singapore"})
print(n_d)
{'IN': 'INDIA', 'US': 'UNITED STATES', 'JP': 'JAPAN', 'SG': 'SINGAPORE'}
#None type
def addition(a, b):
print(a + b)
print(addition(10, 20))
30
None
[Link] 3/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
#function default parameters
def area_of_rectangle(l, b=20):
area = l * b
return area
a = area_of_rectangle(100, 200)
print("area = ", a)
b = area_of_rectangle(2)
print("area = ", b)
area = 20000
area = 40
def show_account_details(name, balance = 1000): # default argument should be placed from right most parameters
print(f"{name} \n {balance}")
show_account_details("John", 10000)
show_account_details("Ken")
accounts = {
"checkings":1958.00,
"savings":3695.50
}
John
10000
Ken
1000
#find number of upper case and lower case letters
s = "HelloWORLD123$"
uc = 0
lc = 0
others = 0
for ch in s:
if [Link]():
uc += 1
elif [Link]():
lc += 1
else:
others += 1
print(f"upper case count = {uc}")
print(f"lower case count = {lc}")
print(f"others count = {others}")
upper case count = 6
lower case count = 4
others count = 4
#display given number in binary, hexadecimal and octal
n = 12
print(f"{n:b}")
print(f"{n:x}")
print(f"{n:o}")
print("{:b}".format(n))
print("{:x}".format(n))
print("{:o}".format(n))
1100
c
14
1100
c
14
[Link] 4/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
#Keyword Arguments
def display_profile(name, age, marks):
print("*"*50)
print(f'''
Name : {name}
Age : {age}
Marks : {marks}
''')
print("*"*50)
# display_profile("John", 30, 25)
# display_profile(name="John", age=30, marks=25) # keyword arguments
display_profile(age=30, marks=25, name="John") # keyword arguments can be any order
**************************************************
Name : John
Age : 30
Marks : 25
**************************************************
# arbitrary arguments
def display_score(name, a, b, c, d):
print(name)
print(a, b, c, d)
display_score("John", 10, 20, 30, 40)
def display_score(name, *m):
print(name)
print(m)
display_score("John", 10, 20, 30, 40)
John
10 20 30 40
John
(10, 20, 30, 40)
def dispaly_score(name, *m):
print(name)
print(m)
a,b,c,d = m
print(a)
print(b)
print(c)
print(d)
dispaly_score("John", 10, 20, 30, 40)
John
(10, 20, 30, 40)
10
20
30
40
def display_score(name, *marks):
print(marks)
subject_count = len(marks)
total = sum(marks)
avg = total / subject_count
print("*"*50)
print(f"Name : {name}")
for m in marks:
print("\t",m)
print(f"total : {total}")
print(f"average : {avg}")
display_score("John", 10, 20, 30, 40)
(10, 20, 30, 40)
**************************************************
Name : John
10
20
30
40
total : 100
average : 25.0
[Link] 5/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
#arbitrary key word arguments
def display_score(name, **m):
print(name)
print(m)
display_score("John", a=10, b=20, c=30, d=40)
John
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
def dispaly_score(name, **m):
print(name)
print(m)
print("Tamil marks : ", m["tamil"])
for k in m:
print(k, m[k])
dispaly_score("John", tamil=10, english=20, maths=30, science=40)
John
{'tamil': 10, 'english': 20, 'maths': 30, 'science': 40}
Tamil marks : 10
tamil 10
english 20
maths 30
science 40
#global scope
x = 10
def access_global():
print("called access_global")
print(x)
print(x)
def try_to_change_global1():
print("try_to_change_global1")
x = 20
try_to_change_global1()
print(x)
def correct_way_to_change():
global x
x = 20
correct_way_to_change()
print(x)
10
try_to_change_global1
10
20
#local scope
def hello():
a = 10
print("hi")
print(a)
hello()
print(a)
hi
10
20000
[Link] 6/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
#tail recursion -> call is after the code to be executed
def reverse(n):
if n == 0:
return
print(n)
reverse(n-1)
reverse(10)
10
9
8
7
6
5
4
3
2
1
#head recursion -> call is before the code to be executed
def reverse(n):
if n == 0:
return
reverse(n-1)
print(n)
reverse(10)
1
2
3
4
5
6
7
8
9
10
# head recursion
def reverse(n):
if n == 0:
return
reverse(n-1) # function call
print(n) # code to be executed
reverse(3)
# |print(1)|
# |print(2)|
# |print(3)|
# __________
1
2
3
#head recursion -> sum of n digits
def reverse_sum(n):
if n == 1:
return n
return n + reverse_sum(n-1)
s = reverse_sum(5)
print("sum = ", s)
sum = 15
[Link] 7/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
#head recursion -> factorial
def fact(n):
if n == 0 or n == 1:
return 1
return n * fact(n - 1)
res = fact(3)
print("result = ", res)
result = 6
#file - read
#try to run file programs in local computer if error occured
fp = open("[Link]", "r")
contents = [Link]()
[Link]()
print(contents)
John
#file - read line by line
fp = open("[Link]", "r")
line1 = [Link]()
# line2 = [Link]()
[Link]()
print(line1)
# print(line2)
John
#file - write - append mode
fp = open("[Link]", "a")
[Link]("\nhello")
[Link]()
fp = open("[Link]", "r")
contents = [Link]()
[Link]()
print(contents)
John
hello
#file - write - write mode
fp = open("[Link]", "w")
[Link]("john\n")
[Link]()
fp = open("[Link]", "r")
contents = [Link]()
[Link]()
print(contents)
john
#file - write - x mode
fp = open("[Link]", "x")
[Link]("john\n")
[Link]()
fp = open("[Link]", "r")
contents = [Link]()
[Link]()
print(contents)
john
#file - deleting file
import os
[Link]("[Link]")
[Link] 8/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
#file - deleting file
import os
if [Link]("[Link]"):
[Link]("[Link]")
print("deleted")
else:
print("file not found")
file not found
#os module
import os
[Link]("new")
# [Link]("new","old")
# [Link]("old")
# help
# print(help("math"))
print(help("os"))
SCHED_IDLE = 5
SCHED_OTHER = 0
SCHED_RESET_ON_FORK = 1073741824
SCHED_RR = 2
SEEK_CUR = 1
SEEK_DATA = 3
SEEK_END = 2
SEEK_HOLE = 4
SEEK_SET = 0
SPLICE_F_MORE = 4
SPLICE_F_MOVE = 1
SPLICE_F_NONBLOCK = 2
ST_APPEND = 256
ST_MANDLOCK = 64
ST_NOATIME = 1024
ST_NODEV = 4
ST_NODIRATIME = 2048
ST_NOEXEC = 8
ST_NOSUID = 2
ST_RDONLY = 1
ST_RELATIME = 4096
ST_SYNCHRONOUS = 16
ST_WRITE = 128
TMP_MAX = 238328
WCONTINUED = 8
WEXITED = 4
WNOHANG = 1
WNOWAIT = 16777216
WSTOPPED = 2
WUNTRACED = 2
W_OK = 2
XATTR_CREATE = 1
XATTR_REPLACE = 2
XATTR_SIZE_MAX = 65536
X_OK = 1
__all__ = ['altsep', 'curdir', 'pardir', 'sep', 'pathsep', 'linesep', ...
altsep = None
confstr_names = {'CS_GNU_LIBC_VERSION': 2, 'CS_GNU_LIBPTHREAD_VERSION'...
curdir = '.'
defpath = '/bin:/usr/bin'
devnull = '/dev/null'
environ = environ({'SHELL': '/bin/bash', 'NV_LIBCUBLAS_VER...AUTH_EPHE...
environb = environ({b'SHELL': b'/bin/bash', b'NV_LIBCUBLAS_...H_EPHEM'...
extsep = '.'
linesep = '\n'
name = 'posix'
pardir = '..'
pathconf_names = {'PC_ALLOC_SIZE_MIN': 18, 'PC_ASYNC_IO': 10, 'PC_CHOW...
pathsep = ':'
sep = '/'
supports_bytes_environ = True
sysconf_names = {'SC_2_CHAR_TERM': 95, 'SC_2_C_BIND': 47, 'SC_2_C_DEV'...
FILE
/usr/lib/python3.10/[Link]
None
[Link] 9/10
12/9/23, 11:09 AM Python unit 4 [Link] - Colaboratory
#math module
import math
print([Link](5))
print([Link](1.7))
print([Link](1.7))
print(math.e)
print([Link])
print([Link](2, 3))
120
1
2
2.718281828459045
3.141592653589793
8.0
#string module
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
s = input("enter a character : ")
if s in string.ascii_uppercase:
print("upper case")
elif s in string.ascii_lowercase:
print("lower case")
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
enter a character : C
upper case
#string module
[Link] 10/10