(L5)Programming Foundation with Python
(L5)Programming Foundation with Python
with Python
Lesson 5 Functions
Program:
Output:
def thing():
print('Hello') Hello
print('Fun')
Fun
thing() Zip
print('Zip') Hello
thing()
Fun
There are two kinds of functions in Python.
Built-in functions
The module object contains the functions and variables defined in the module.
To access one of the functions, you have to specify the name of the module and the
name of the function, separated by a dot (also known as a period).
import random
number = random.randint(2,20)
print(number)
print(math.sqrt(number))
print(math.factorial(number))
Class Activity: To display who is the winner.
import random
print("Computer:: ",random.randint(1,6))
if(ans == "y"):
print("Player:: ",random.randint(1,6))
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
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 printGreeting():
print(“Welcome to my program…”)
print(“*” * 40)
Example: just define the function
number = 89
print(number,“* 4 =”,number * 4)
def printGreeting():
print(“*” * 40)
print(“Welcome to my program…”)
print(“*” * 40)
print(“Hello”)
print(number,“/ 3 =”,number/3)
Definitions and Uses
● Once we have defined a function, we can call (or invoke) it
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.
print(“Hello”)
result = addto5(number)
print(result)
Function Definition and Function Invoking(Calling)
def greet(lang):
Function Calling
if lang == 'es':
>>> greet('en')
print('Hola') Hello
elif lang == 'fr':
>>> greet('es')
Hola
print('Bonjour')