24. Functions
def
keyword.24.1. Functions without parameters
def
keyword and has empty parentheses.def
line has a colon at the end and the code for the definition is indented.show_welcome()
.def show_welcome():
print("Hello python user!")
show_welcome()
Note
Without the return statement, the function will return None
.
Tasks
Write a function called
print_name
that prints your name.Write a function called
countdown
that counts down from 5 to 1, printing each number.
24.2. Functions with parameters
name
is the parameter, and "beginner"
and "user"
are the arguments.def show_welcome(name):
print("Hello " + name)
show_welcome("beginner")
show_welcome("user")
24.3. Functions with default parameters
def employee_info(name="N. U. Guy", salary=20000):
print(f"{name} earns ${salary} per year")
employee_info()
employee_info(name="Nu Guy", salary=25000)
employee_info("B. Ginner", 30000)
Tasks
Write a function called
player_info
with 3 default parameters for their user_name, their number of game lives and their game health status and print an example using it.
24.4. Functions returning information
def convert_inches_to_centimetres(inches):
return inches * 2.54
length_cm = convert_inches_to_centimetres(8)
print(length_cm)
def area_of_rectangle(length, width):
return length * width
area = area_of_rectangle(9, 7)
print(area)
+
between the text strings.str()
is used to turn age
, which is a integer, into a string.def name_age_greeting(name, age):
return "Hello " + name + ", you are " + str(age) + " years old."
print(name_age_greeting("Peter", 21))
print(name_age_greeting("Paul", 24))
print(name_age_greeting("Mary", 19))
Tasks
Define a function
convert_cm_to_m(cm)
that returns the result of converting a length in cm to metres.Define a function
convert_m_to_cm(m)
that returns the result of converting a length in metres to cm.Define a function
area_square(length)
that returns the area of a square.Write a function called
random_greeting
that returns a random greeting that is randomly chosen from a list of greetings:["Hi", "Hello", "G'day"]
. See: https://www.w3schools.com/python/ref_random_choice.asp
24.5. *args
*args
allow a function to take any number of positional arguments (non keyword arguments).*num
allows a variable number of arguments to be passed in to be added in the multi_add
function.num
are multiple arguments.multi_add(2,5)
, there are 2 arguments 2, 5.multi_add(1, 3, 5, 7, 9)
, there are 5 arguments 1, 3, 5, 7, 9.def multi_add(*num):
sum = 0
for n in num:
sum = sum + n
return sum
print(multi_add(2, 5))
print(multi_add(1, 3, 5, 7, 9))