Python Essentials
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.
# SYNTAX: How to declare a user-defined function
def function_name (parameter_1, parameter_2, …):
calculation or action
return x
# 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
Python Functions Example:
def my_function():
print("Welcome") # This function only prints Welcome
print("*" * 30) # and draws a small line of stars *
# Notice: this function does NOT return any data value
# to call function, simply write fn_sample()
my_function ()
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’
# Calling function fn_sqr(a). We have to pass a parameter ‘a’. Suppose a = 3
x = fn_sqr(3) # Output >>> 9 will be stored in variable x. We can print(x)
print(x)
# 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
Python Functions Example:
# Function => convert celsius into fahrenheit
def c2f(celsius):
f = (celsius * 9/5) + 32 # this is standard formula of getting fahrenheit
return f # it returns a value f as temperature in fahrenheit
# 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
Python Functions Exercise:
a) Define a function PKR2USD to convert provided rupee value into US$, where $1=PKR160
𝟓
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
Python: List, Tuple and Dictionary
The concept of arrays has many aspects in Python. List, Dictionary, Set and Tuple are sort of array or collection, that
contains data. They are also considered as data types in Python. You may store millions of records in these collection.
List: [ ] a collection that is ordered and changeable. It allows duplicate members.
Tuple: ( ) a collection that is ordered and unchangeable. It allows duplicate members.
Set: { } a collection that is unordered and unindexed, but not-duplicate.
Dictionary: { } collection that is unordered, changeable and indexed, but not-duplicate.
Python List Example:
cityList = ['Karachi', 'Lahore', 'Islamabad', 'Peshawar', 'Quetta'] # example list
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
Python Project: User Login
# *******************************************
# Python Project: USER LOGIN MODULE
# *******************************************
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
Python Project: List/Tuple Data Manipulation
# >>> Let consider following 2D data of students are saved in a system
student_data = [(101, 'Farhan', 'M', 'JavaProg', 78, 88, 68, 81, '0300‐2644166'),
(102, 'Fatima', 'F', 'WebDevel', 69, 75, 70, 78, '0333‐4844655'),
(103, 'Jibran', 'M', 'Database', 79, 89, 74, 80, '0321‐3894898'),
(104, 'Salman', 'M', 'JavaProg', 70, 65, 72, 76, '0300‐2433121'),
(105, 'Zainab', 'F', 'Database', 77, 80, 82, 72, '0333‐2463111'),
(106, 'Ayesha', 'F', 'WebDevel', 82, 70, 64, 76, '0334‐8894326')
]
# >>> 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
Python Project: Number Game
# *********************************************
# Python Project: GUESS THE SECRET NUMBER GAME
# *********************************************
# Error Exception is NOT taken.
import random # importing python library for random number
num = random.randint(1, 9) # this limits random number b/w 1 to 9
guess = int(input("Guess! enter a number b/w 1 to 9: "))
count = 1
while num != guess: # while loop, until condition num = guess is met.
count += 1 # counting number of attempts or chances
print("You missed.", "Have chance no.", count, " try again.")
guess = int(input("Enter your best guess b/w 1 to 9: "))
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.")
# *********************************************