Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
41 views

Pythonlearn 04 Functions

This document discusses functions in Python. It defines functions as reusable blocks of code that take arguments as input, perform operations, and optionally return a result. There are two types of functions - built-in functions provided by Python like print() and user-defined functions. Functions are defined using the def keyword and called by their name. Arguments are passed into functions during calls and parameters refer to the variables in the function definition. Functions allow for code reuse and modular programming.

Uploaded by

Atal Bihari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Pythonlearn 04 Functions

This document discusses functions in Python. It defines functions as reusable blocks of code that take arguments as input, perform operations, and optionally return a result. There are two types of functions - built-in functions provided by Python like print() and user-defined functions. Functions are defined using the def keyword and called by their name. Arguments are passed into functions during calls and parameters refer to the variables in the function definition. Functions allow for code reuse and modular programming.

Uploaded by

Atal Bihari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Functions

Chapter 4
Stored (and reused) Steps
def
thing(): Program:
print('Hello') Output:
def thing():
print('Fun') print('Hello')
print('Fun') Hello
thing() Fun
thing()
print('Zip') Zip
print('Zip') thing()
Hello
Fun
thing()
We call these reusable pieces of code “functions”
Python Functions
• There are two kinds of functions in Python.

- Built-in functions that are provided as part of Python - print(),


input(), type(), float(), int() ...

- Functions that we define ourselves and then use

• We treat the built-in function names as “new” reserved words


(i.e., we avoid them as variable names)
Function Definition
• In Python a function is some reusable code that takes
arguments(s) as input, does some computation, and then returns
a result or results

• We define a function using the def reserved word

• We call/invoke the function by using the function name,


parentheses, and arguments in an expression
Argument

big = max('Hello world')


Assignment
'w'

Result
>>> big = max('Hello world')
>>> print(big)
w
>>> tiny = min('Hello world')
>>> print(tiny)

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

'Hello world' max() 'w'


(a string) (a string)
function

Guido wrote this code


Max Function
A function is some
>>> big = max('Hello world') stored code that we
>>> print(big)
use. A function takes
w
some input and
def max(inp):
produces an output.
blah
'Hello world' blah 'w'
for x in inp:
(a string) blah
(a string)
blah

Guido wrote this code


Type Conversions
>>> print(float(99) / 100)
• When you put an integer 0.99
>>> i = 42
and floating point in an >>> type(i)
expression, the integer <class 'int'>
is implicitly converted to >>> f = float(i)
>>> print(f)
a float 42.0
>>> type(f)
• You can control this with <class 'float'>
the built-in functions int() >>> print(1 + 2 * float(3) / 4 – 5)
and float() -2.5
>>>
String >>> sval = '123'
>>> type(sval)
<class 'str'>
Conversions >>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• You can also use int() TypeError: cannot concatenate 'str'
and 'int'
and float() to convert >>> ival = int(sval)
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()
Functions of Our Own…
Building our Own Functions
• We create a new function using the def keyword followed by
optional parameters in parentheses

• We indent the body of the function

• This defines the function but does not execute the body of the
function

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

x = 5
print('Hello')

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

• This is the store and reuse pattern


x = 5
print('Hello')

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

print('Yo')
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
Arguments
• An argument is a value we pass into the function as its input
when we call the function

• We use arguments so we can direct the function to do different


kinds of work when we call it at different times

• We put the arguments in parentheses after the name of the


function
big = max('Hello world')
Argument
Parameters
>>> def greet(lang):
... if lang == 'es':
A parameter is a variable which ... print('Hola')
... elif lang == 'fr':
we use in the function definition. ... print('Bonjour')
It is a “handle” that allows the ... else:
... print('Hello')
code in the function to access ...
>>> greet('en')
the arguments for a particular Hello
function invocation. >>> greet('es')
Hola
>>> greet('fr')
Bonjour
>>>
Return Values
Often a function will take its arguments, do some computation, and
return a value to be used as the value of the function call in the
calling expression. The return keyword is used for this.

def greet():
return "Hello" Hello Glenn
Hello Sally
print(greet(), "Glenn")
print(greet(), "Sally")
Return Value
>>> def greet(lang):
... if lang == 'es':
• A “fruitful” function is one ... return 'Hola'
... elif lang == 'fr':
that produces a result (or ... return 'Bonjour'
return value) ... else:
... return 'Hello'
...
• The return statement ends >>> print(greet('en'),'Glenn')
the function execution and Hello Glenn
>>> print(greet('es'),'Sally')
“sends back” the result of Hola Sally
the function >>> print(greet('fr'),'Michael')
Bonjour Michael
>>>
Arguments, Parameters, and
Results
>>> big = max('Hello world') Parameter
>>> print(big)
w
def max(inp):
blah
blah
'Hello world' for x in inp: 'w'
blah
blah
Argument return 'w'
Result
Multiple Parameters / Arguments
• We can define more than one
parameter in the function def addtwo(a, b):
definition added = a + b
return added
• We simply add more arguments
x = addtwo(3, 5)
when we call the function print(x)

• We match the number and order 8


of arguments and parameters
Void (non-fruitful) Functions

• When a function does not return a value, we call it a “void”


function

• Functions that return values are “fruitful” functions

• Void functions are “not fruitful”


To function or not to function...
• Organize your code into “paragraphs” - capture a complete
thought and “name it”

• Don’t repeat yourself - make it work once and then reuse it

• If something gets too long or complex, break it up into logical


chunks and put those chunks in functions

• Make a library of common stuff that you do over and over -


perhaps share this with your friends...
Summary
• Functions • Arguments
• Built-In Functions • Results (fruitful functions)
• Type conversion (int, float) • Void (non-fruitful) functions
• String conversions • Why use functions?
• Parameters
Exercise

Rewrite your pay computation with time-and-a-


half for overtime and create a function called
computepay which takes two parameters ( hours
and rate).

Enter Hours: 45
Enter Rate: 10

Pay: 475.0
475 = 40 * 10 + 5 * 15

You might also like