Python Functions
Python functions are essential pieces of code that can be reused across your program. Learn how to define and call functions, handle local variables, pass parameters, and more in this comprehensive guide. Get a deeper understanding of functions in Python to enhance your coding skills.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Python Functions for Computer Science 105 Dr. Neil Simonetti for a more complete treatment of functions see https://python.swaroopch.com/functions.html
What is a Function A function is piece of code that is written once, but can be used from multiple places in your code. The act of using this code is known as calling the function. A function is recognized by having (parentheses) following the function s name. The parentheses may contain objects, known as parameters or arguments when used in this fashion, or they may contain nothing. You have already used some built-in functions, for example: print, input, range, str, int, float
Defining a Function The def keyword introduces the function. A colon [ : ] ends the introduction to the function. The body of the function is indented. A function must be defined before it is used. def ErrorMessage(): print("Aaack! An error occurred!") x = input("What should we do about it? ") print("You go do that. Thanks.")
Calling a Function def ErrorMessage(): # print an error message print("Aaack! An error occurred!") x = input("What should we do about it? ") print("You go do that. Thanks.") Function definition num = int(input("Enter a positive integer: ")) if num < 1: ErrorMessage() print("I don t know what to do with this number!") ErrorMessage() print("The program is done.") Function calls
Function Variables are Local When a variable is used in a function, it exists only in that function. A function s local variables cannot be used outside the function. The function cannot use variables created outside of the function unless the global statement is used. def MyFunc(): x = 17 print("this x is", x) x = 12 MyFunc() print("that x is", x) def MyFunc(): global x x = 17 print("this x is", x) x = 12 MyFunc() print("that x is", x) This program prints: this x is 17 that x is 17 This program prints: this x is 17 that x is 12 Try to avoid global variables when possible.
Parameters You can avoid using global variables by passing information into functions with parameters (contained in parentheses). These parameters become local variables. Modifying parameters does not change the values of the identifiers used to pass in the information. This is not true if what is passed as a parameter is a complex data structure, like a list. For more on this, take CSci180, where you will learn about pointers and references. When a function with parameters is called, the parameters may be identifiers, literals, or expressions.
Examples of Parameters def Did_I_Pass(grade): if grade >= 60: print("Pass") else: print("Fail") x = 37 Did_I_Pass(78) Did_I_Pass(x) Did_I_Pass(x+56.3) def PrintWithTax(amt,rate): # add sales tax amt = amt * (1 + rate) print("You owe",amt) This program prints: You owe 110.0 You owe 477.0 Values: 70 450 This program prints: Pass Fail Pass x = 70 amt = 450 PrintWithTax(x+30, 0.10) PrintWithTax(amt, 0.06) print("Values:",x,amt)
return Like the break statement inside loops, a return statement in a function will immediately end the function and return program control where it left off when calling the function. def BorrowMoney(amt): x = float(input("How much money do you have now? ")) if x < amt: # not worth asking return y = input("Can I borrow "+str(amt)+" for today?") if y == "Yes": print("Thank you so much.")
Returning a value A function can return a value by placing a literal, identifier, or expression after the return statement. This value will be substituted wherever the function call was placed. def Minimum (a, b): x = int(input("Enter integer: ")) #return smaller y = int(input("Again, please: ")) if a < b: z = Minimum (x, y) return a print("The smaller one is", z) else: print("The smaller of 4 and", x,\ return b print(Minimum("blue", "black")) print(Minimum("Blue", "black")) is continued on the next line. "is", Minimum (4, x)) A backslash [ \ ] tells the Python interpreter that the statement
Returning a value A function can return a value by placing a literal, identifier, or expression after the return statement. This value will be substituted wherever the function call was placed. x = int(input("Enter integer: ")) y = int(input("Again, please: ")) z = Minimum (x, y) print("The smaller one is", z) print("The smaller of 4 and", x,\ "is", Minimum (4, x)) print(Minimum("blue", "black")) print(Minimum("Green", "black")) Sample output: Enter integer: 8 Again, please: 37 The smaller one is 8 The smaller of 4 and 8 is 4 black Green Determining the lesser of two strings is done by ASCII value, where G comes before b .
exit() Like the return statement for functions, the exit() function immediately ends the program. x = int(input("Enter a positive integer: ")) if x < 1: # no point in continuing exit() y = int(input("Enter another positive integer: ")) if y < 1: exit() print("The smaller integer is:", Minimum(x, y))
Why Use Functions At All? Using functions is preferable to copying (nearly) identical code in several places in your program. If an error needs to be fixed or the code needs to be updated, any change only needs to be made in one place. Using functions makes a program easier to understand. By dividing your program into compartments, someone reading your code can more easily understand how you are accomplishing your task. Functions can be recycled into future programs. If you write a function to perform a certain task, and you need the same task done in another program, the function can more easily be copied into the new program. (Even better if you create your own library of importable functions)