Python Essentials - Part 2
Python Essentials - Part 2
Part 2
Concepts and Examples
by
M. Imran
M. Imran 2019
Python Function
# What is function
A function is a set of statements that take inputs, do defined tasks,
computation; and may return output. Function avoids repetitive tasks.
# How to call a function
function_name (parameter_1, parameter_2, …)
# e.g.; myfunction(2,3) fn_print() fn_sqr(4) etc.
=> function may accept zero, one, or many parameters/arguments.
=> function may return a single value, an array/list, or nothing.
=> There are also many default Python functions: print(), input() etc.
M. Imran 2019
def fn_sqr(a): # This function performs Square of a given value ‘a’
b = a ** 2 # syntax for a2 (a square) is a ** 2
return b # the function gives/returns answer as variable ‘b’
# Function => find area of circle = π r2
def circle_area (r):
a = 3.1415 * r**2 # constant value of pi π = 3.1415
return a
print(circle_area(5)) # directly use function with parameter 5 inside print()
M. Imran 2019
# Function => calculate grades
def grade(obt, total): # this function takes two parameters, ‘obt’ and ‘total’
c = (obt/total)*100
if c >= 80:
g = 'A1'
elif c >= 70 and c < 80:
g = 'A'
elif c >= 60 and c < 70:
g = 'B'
elif c >= 50 and c < 60:
g = 'C'
elif c >= 40 and c < 50:
g = 'D'
elif c >= 33.33 and c < 40:
g = 'E'
else:
g = 'Fail'
return g # this function returns a single string as g
# Now call function grade(obt, total)
print("Grade: \t\t ", grade(410, 500))
M. Imran 2019
𝟓
b) Define a function f2c to convert Fahrenheit value into Celsius. °𝑪 °𝑭 𝟑𝟐
𝟗
𝟏
c) Define a function area_tri to get the area of triangle. 𝑻𝒓𝒊_𝑨𝒓𝒆𝒂 𝒃𝒂𝒔𝒆 𝒉𝒆𝒊𝒈𝒉𝒕
𝟐
d) Define a function to determine the land area of plot that takes length and width in
𝑳𝒆𝒏𝒈𝒕𝒉𝒇𝒆𝒆𝒕 𝑾𝒊𝒅𝒕𝒉𝒇𝒆𝒆𝒕
feet, and returns area in square yards. 𝑨𝒓𝒆𝒂 𝒊𝒏 𝑺𝒒. 𝒀𝒂𝒓𝒅𝒔
𝟗
e) Define a function that computes the amount of income tax on a given annual salary.
Annual Salary Slab Income Tax Rate
Less than 120,000 0%
120,000 to 240,000 2.5%
240,000 to 500,000 5.0%
500,000 to 1200,000 10.0%
Greater than 120,000 15%
M. Imran 2019
fb_friends = ['Ahmed', 'Faiz', 'Imran', 'Steve'] # list contains 4 values, index 0 to 3
print(fb_friends[1]); print(fb_friends[2:]); print(fb_friends[‐1])
my_contact = [['imran', '0300‐2433121'],
['faraz', '0321‐4332890'],
['jibran', '0333‐3588492']] # lists within list
matrix_list = [[201, 201, 203], # matrix_list is like a two‐dimensional array
[404, 405, 406],
[608, 609, 600]]
print(matrix_list[0][0], matrix_list[0][1], matrix_list[0][2])
print(matrix_list[1][0], matrix_list[1][1], matrix_list[1][2])
print(matrix_list[2][0], matrix_list[2][1], matrix_list[2][2])
M. Imran 2019
login_list = [('[email protected]', 'pw1234'), ('[email protected]', 'karachi123'),
('[email protected]', '2001pak'), ('[email protected]', '1234')] # stored login data in list
id = "[email protected]" # provided user‐id as variable id
pw = "2001pak" # provided password as variable pw
# make tuple (id, pw) to put inside if condition
if (id, pw) in login_list: # notice: search paired tuple (id, pw) in stored login_list
print("Login successful \nwelcome", id[:id.find("@")]) # string manipulation
elif (id, pw) not in login_list:
print("Invalid user name or password")
# *******************************************
M. Imran 2019
# >>> To fetch all student names and department (two fields only).
# Suppose variables for list headers or tuple are a = RN, b = Name, c = M/F Gender,
d = Department, e = Marks‐1, f = Marks‐2, g = Marks‐3, h = Marks‐4, i = Contact
for (a, b, c, d, e, f, g, h, i) in student_data: # for (tuple) in list[]:
print(b, d) # getting print of two fields for all students,
# >>> To fetch specific fields of a student data, with a given roll‐number. if
condition roll_no == (index_variable):
roll_no = 104
for (a, b, c, d, e, f, g, h, i) in student_data:
if roll_no == (a): # if condition matches given roll_no=104
print(a, b, d, i) # and only prints 4 fields for this data row.
# >>> To search specific student name and his fields, let variable sname = "Jibran", M. Imran 2019
and put it in condition if sname = (index_variable):
sname = "Jibran"
for (a, b, c, d, e, f, g, h, i) in student_data:
if sname == (b):
print("Search Results: \n", "Name: ", b, "\n", "Depart: ", d)
print(" Percentage:", 100*(e+f+g+h)/400, "%")
# >>> To get group data of all "Female"
print("Name\t", "Gen\t", "Depart\t\t", "Marks Sem‐1\t", "Marks Sem‐2\t", "Marks Sem‐
"Contact \t")
3\t", "Marks Sem‐4\t", # This print just produces fields headings
for (a, b, c, d, e, f, g, h, i) in student_data:
if "F" == (c):
print(b, "\t", c, "\t\t", d, "\t\t", e, "\t\t", f, "\t\t\t", g, "\t\t\t", h,
"\t\t\t", i)
# >>> To get data with respect to specific subject, say "Database"
print("Name\t", "Gen\t", "Depart\t\t", "Marks Sem‐1\t", "Marks Sem‐2\t", "Marks Sem‐
"Contact \t")
3\t", "Marks Sem‐4\t",
for (a, b, c, d, e, f, g, h, i) in student_data:
if "Database" == (d):
print(b, "\t", c, "\t\t", d, "\t\t", e, "\t\t", f, "\t\t\t", g, "\t\t\t", h,
"\t\t\t", i)
M. Imran 2019
print("You guessed correctly, congratulations")
print("The number was: ", num)
if count <= 3: # if condition whether success was within 3 attempts
print("As you guessed within 3 attempts, you got a Jackpot Price !")
elif count > 3:
print("It took you", count, "attempt(s) to guess correctly. \nSorry NO Price.")
# *********************************************