0% found this document useful (0 votes)
8 views

CS111 2020 SWPart Lect12 Python Functions

Uploaded by

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

CS111 2020 SWPart Lect12 Python Functions

Uploaded by

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

CS111 – Fundamentals of Computer Science

Functions

Sabah Sayed
List Example
Given a list of prices update it by adding 7% of tax to each price
prices = [1.10, 0.99, 5.75]
for item_price in prices:
print ("Original Price:", item_price, "; tax due:", item_price * 0.07)
print (prices)

Note: prices list are not


changed

Q) Can you update the prices


list to include the prices +
taxes?
Two ways to update list data
Using while loop Using for loop

prices = [1.10, 0.99, 5.75] prices = [1.10, 0.99, 5.75]


i=0 for i in range(len(prices)):
while i < len(prices): prices[i] *= 1.07
prices[i] *= 1.07
i += 1 print (prices)
print (prices)

o/p
Create empty list
# Create empty list
mylist = []
# Use + operator to add an element to the list
mylist += [“Hello”]
mylist += [“first”]
mylist += [“year”]
# Also use append method to add element to the list
mylist .append(“Students”)
print(mylist )
Write custom Functions in Python
• Function:
– collection of statements within a program that can be called upon to perform
a specific action
• Advantages of Functions:
– a technique to break up complicated problems into simple (i.e., organize your
program)
– reusable blocks of code
– Collaboration: divide the work among the team members
• e.g., built-in functions: len, print,range
• Custom function syntax:
def funName(): Note: The funName
follow the same rules
stmts of varName
Example: Functions in Python
def printHello(): # here you only define the function
print("Hello world")

##### main program

printHello() # here we call the function (by writing its name)


# to execute its code
Example
Write functions to draw rectangle

def top():
print ("*****")
def side():
print ("* *")
# draw a rectangle!
top()
for x in range(5):
side()
top()
Example
# define the top/bottom of the shape
Write functions to draw the def top():
print ("#####")
following: # define the next level of the shape
def level1():
print ("# #")
# define the next level of the shape
def level2():
print (" # # ")
# define the middle of the shape
def middle():
print (" # ")
# call the functions to draw the shape
top()
level1()
level2()
middle()
level2()
level1()
top()
Function Local Variables
• Local variables def square():
– define variables inside num = 2
functions print ("Square of", num, "is", num**2)
– Can only be accessed inside def cube():
the function
num = 3
– Different functions may have
the same local variable name print ("Cube of", num, "is", num**3)
###### main program
square()
cube()
Function Argument Variables
• Argument variables (i.e., def square(num):
parameters) print ("Square of", num, "is", num**2)
– automatically declared every def cube(num):
time you call your function print ("Cube of", num, "is", num**3)
– A function can take any ####main program
number of arguments square(2)
cube(3)
Example
Write a function to compute the average of three numbers
def average(num1, num2, num3):
sum = num1+num2+num3
avg = sum / 3
print (avg)
# call the function with 3 arguments
x=100
y=90
z=92
average(x,y,z)
Function Arguments: Passing by value
def swap(x,y):
• Passing by value temp=x
– Make a copy of the variable x=y
– Send the copy to the function y=temp
10 20
– Any update in the sent copy
will not affect on the main num1=10
variable
num2=20
print(num1,num2)
swap(num1,num2)
print(num1,num2)
What is the o/p?
def change_me(v):
print ("function: I got:", v)
# change the argument variable
v = 10
print ("function: argument is now:", v)
# main program
myvar = 5
print ("starting with:", myvar)
change_me(myvar)
print ("ending with:", myvar)
Function Return value
• Use the keyword “return” to return a value from a function
• The return statement will immediately cause a function to end and
send back whatever value is attached to the return statement.
def power(n,m):
result=n**m
return result
#####main program
n=int(input("Enter your base"))
m=int(input("Enter your power"))
my_Pow=power(n,m)
print (n,"**",m,"=", my_Pow)
Example
Write a function to check if a given number is even or odd, then return
“even” or “odd”
def check(a):
if a % 2 == 0:
return "even"
return "odd" # here, no need to write "else"
#######main program
answer1 = check(3)
print ("Return value #1:", answer1)
print ()
answer2 = check(4)
print ("Return value #2:", answer2)
Function Return multiple values
1 2
def powers(a): def swap(x,y):
pow_2 = a**2 temp=x
pow_3 = a**3 x=y
pow_4 = a**4 y=temp
return pow_2, pow_3, pow_4 return x,y
##### main program
x,y,z = powers(2) num1=10
print (x,y,z) num2=20
print(num1,num2)
num1,num2=swap(num1,num2)
print(num1,num2)
What is the o/p?
def myfun(x, y): ######## main program
print('starting loopy:', x, y) x=1
while x < y: y = 10
x += 2 y = myfun(x, y)
y -= 2 print('after first call:', x, y)
print('after loop:', x, y) myfun(y, x)
return x print('after second call:', x, y) starting loopy: 1 10
after loop: 7 4
after first call: 1 7
starting loopy: 7 1
after loop: 7 1
after second call: 1 7
Example
def even_odd_print():
• Write a function that asks the # get start & end
user to enter a start, end and start = int(input("Start number: "))
the word "even" or "odd". If the end = int(input("End number: "))
# get even or odd
user enters “even”, then the choice = input("'even' or 'odd'? ")
function prints all even numbers # generate loop
between start and end. for i in range(start, end+1):
if choice == "even" and i % 2 == 0:
Otherwise, all odd numbers print (i)
between start and end will be if choice == "odd" and i % 2 != 0:
printed print (i)
#### main program
even_odd_print()
Homework
• Write a search function which take a list of numbers and a
target. Then it will search about the target in the given list
and return “found” or “not found”
• Note: Take the list and target from the user and pass them to
the search function

You might also like