
Syntax: Functions in Python
Creating your own custom functions in Python.
Practice: Greeting User Function
-
Define a function named
greet_user. -
Inside the function, use the print function to output the string
"Hello, user!". -
After the function definition, call your
greet_userfunction. -
Run your code and confirm that the output is
"Hello, user!".
HINT*: Click here for a hint
> "Hello, user!"
SOLUTION*: Click here for an example solution
def greet_user():
print("Hello, user!")
greet_user()
Practice: Function to Print a Favorite Quote
-
Define a function named
favorite_quote. -
Inside the function, use the
printfunction to output your favorite quote. -
After the function definition, call your
favorite_quote function. -
Run your code and confirm that the output is your favorite quote.
HINT*: Click here for a hint
> "The only way to do great work is to love what you do." - Steve Jobs
SOLUTION*: Click here for an example solution
def favorite_quote():
print('"The only way to do great work is to love what you do." - Steve Jobs')
favorite_quote()
Practice: Function to Print a List of Fruits
-
Define a function named
print_fruits. -
Inside the function, define a list with the names of some fruits.
-
Also in the function, use a
forloop to print each fruit in the list. -
After the function definition, call your
print_fruitsfunction. -
Run your code and confirm that the output is a list of fruits, each printed on a new line.
HINT*: Click here for a hint
> "apple"
> "banana"
> "cherry"
SOLUTION*: Click here for an example solution
def print_fruits():
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
print_fruits()
Practice: Function to Print a Countdown
-
Define a function named
countdown. -
Inside the function, use a
forloop and the range function to count down from 5 to 1 (inclusive), printing each number on a new line. -
After the last number, print the string
"Blast off!". -
After the function definition, call your countdown function.
-
Run your code and confirm that the output is a countdown from
5to1, followed by"Blast off!".
HINT*: Click here for a hint
>5 4 3 2 1 Blast off!
SOLUTION*: Click here for an example solution
def countdown():
for i in range(5, 0, -1):
print(i)
print("Blast off!")
countdown()