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

Pythonlearn 04 Functions

A Python function is reusable code that takes arguments, performs computations, and returns results. The document discusses built-in functions like print() and max() as well as user-defined functions. It provides examples of calling functions and passing arguments. Functions allow code to be reused by calling the function multiple times.

Uploaded by

Hưng Minh Phan
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)
29 views

Pythonlearn 04 Functions

A Python function is reusable code that takes arguments, performs computations, and returns results. The document discusses built-in functions like print() and max() as well as user-defined functions. It provides examples of calling functions and passing arguments. Functions allow code to be reused by calling the function multiple times.

Uploaded by

Hưng Minh Phan
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/ 7

10/01/21

Stored (and reused) Steps


def
thing(): Program:

Functions print('Hello')
print('Fun')
def thing():
print('Hello')
Output:

Chapter 4 print('Fun') Hello


thing() Fun
thing()
print('Zip') Zip
print('Zip') thing()
Hello
Python for Everybody Fun
www.py4e.com thing()
We call these reusable pieces of code “functions”

1 2

Python Functions Function Definition


• There are two kinds of functions in Python. • In Python a function is some reusable code that takes
arguments(s) as input, does some computation, and then returns
- Built-in functions that are provided as part of Python - print(),
a result or results
input(), type(), float(), int() ...

- Functions that we define ourselves and then use • We define a function using the def reserved word

• We treat the built-in function names as “new” reserved words • We call/invoke the function by using the function name,
(i.e., we avoid them as variable names) parentheses, and arguments in an expression

3 4
10/01/21

Argument

big = max('Hello world')


Max Function
A function is some
>>> big = max('Hello world') stored code that we
Assignment
>>> print(big)
'w' use. A function takes
w
some input and
Result produces an output.
>>> big = max('Hello world')
>>> print(big) 'Hello world' max() 'w'
w (a string)
>>> tiny = min('Hello world')
(a string) function
>>> print(tiny)

>>> Guido wrote this code

5 6

Max Function Type Conversions


A function is some
>>> print(float(99) / 100)
>>> big = max('Hello world') stored code that we
• When you put an integer 0.99
>>> print(big)
use. A function takes >>> i = 42
w and floating point in an
some input and >>> type(i)
expression, the integer <class 'int'>
produces an output.
def max(inp): is implicitly converted to >>> f = float(i)
blah >>> print(f)
'Hello world' blah 'w' a float 42.0
for x in inp:
(a string) (a string) >>> type(f)
blah
blah
• You can control this with <class 'float'>
the built-in functions int() >>> print(1 + 2 * float(3) / 4 – 5)
and float() -2.5
Guido wrote this code >>>

7 8
10/01/21

String >>> sval = '123'


>>> type(sval)

Conversions <class 'str'>


>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• You can also use int() TypeError: cannot concatenate 'str'
and float() to convert and 'int'
>>> ival = int(sval) Functions of Our Own…
between strings and >>> type(ival)
<class 'int'>
integers >>> print(ival + 1)
124
• You will get an error if the >>> nsv = 'hello bob'
>>> niv = int(nsv)
string does not contain Traceback (most recent call last):
numeric characters File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()

9 10

Building our Own Functions print_lyrics():


print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')

x = 5
• We create a new function using the def keyword followed by print('Hello')
optional parameters in parentheses
def print_lyrics():
• We indent the body of the function print("I'm a lumberjack, and I'm okay.") Hello
print('I sleep all night and I work all day.')
Yo
• This defines the function but does not execute the body of the 7
print('Yo')
function x = x + 2
print(x)
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')

11 12
10/01/21

Definitions and Uses x = 5


print('Hello')

def print_lyrics():
• Once we have defined a function, we can call (or invoke) it print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
as many times as we like
print('Yo')
• This is the store and reuse pattern print_lyrics()
x = x + 2
Hello
print(x) Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7

13 14

Arguments Parameters
• An argument is a value we pass into the function as its input >>> def greet(lang):
... if lang == 'es':
when we call the function
A parameter is a variable which ... print('Hola')
... elif lang == 'fr':
• We use arguments so we can direct the function to do different we use in the function definition. ... print('Bonjour')
It is a “handle” that allows the ... else:
kinds of work when we call it at different times ... print('Hello')
code in the function to access ...
• We put the arguments in parentheses after the name of the >>> greet('en')
the arguments for a particular Hello
function
function invocation. >>> greet('es')
big = max('Hello world') Hola
>>> greet('fr')
Bonjour
Argument >>>

15 16
10/01/21

Return Values Return Value


>>> def greet(lang):
Often a function will take its arguments, do some computation, and ... if lang == 'es':
return a value to be used as the value of the function call in the • A “fruitful” function is one ... return 'Hola'
... elif lang == 'fr':
calling expression. The return keyword is used for this. that produces a result (or ... return 'Bonjour'
return value) ... else:
... return 'Hello'
...
def greet(): • The return statement ends >>> print(greet('en'),'Glenn')
return "Hello" Hello Glenn the function execution and Hello Glenn
>>> print(greet('es'),'Sally')
Hello Sally “sends back” the result of Hola Sally
print(greet(), "Glenn") the function >>> print(greet('fr'),'Michael')
print(greet(), "Sally") Bonjour Michael
>>>

17 18

Arguments, Parameters, and


Multiple Parameters / Arguments
Results
>>> big = max('Hello world') Parameter • We can define more than one
>>> print(big) parameter in the function def addtwo(a, b):
w definition added = a + b
def max(inp): return added
blah
blah • We simply add more arguments
'Hello world' 'w' x = addtwo(3, 5)
for x in inp: when we call the function print(x)
blah
blah
Argument return 'w' • We match the number and order 8
Result
of arguments and parameters

19 20
10/01/21

Void (non-fruitful) Functions To function or not to function...


• Organize your code into “paragraphs” - capture a complete
thought and “name it”
• When a function does not return a value, we call it a “void”
function • Don’t repeat yourself - make it work once and then reuse it

• Functions that return values are “fruitful” functions • If something gets too long or complex, break it up into logical
chunks and put those chunks in functions
• Void functions are “not fruitful”
• Make a library of common stuff that you do over and over -
perhaps share this with your friends...

21 22

Exercise
Summary Rewrite your pay computation with time-and-a-
half for overtime and create a function called
• Functions • Arguments
computepay which takes two parameters ( hours
• Built-In Functions • Results (fruitful functions) and rate).
• Type conversion (int, float) • Void (non-fruitful) functions Enter Hours: 45
• String conversions • Why use functions? Enter Rate: 10

• Parameters Pay: 475.0


475 = 40 * 10 + 5 * 15

23 24
10/01/21

Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance ...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan


School of Information

… Insert new Contributors and Translators here

25

You might also like