Functions are key elements of programming. They are used in most programming languages.
Functions allow you to break your code into smaller pieces. That way your code is easier to manage and easier to understand.
Functions also enable you to reuse code in multiple places in your application. That way you save time and make your code easier to read.
In the first half of this post, we will explain what are Python functions, how to define them, and how to call them.
In the second part of this post, we will create a small application in which we will use Python functions. That way you can see functions in action.
How to define a Python function?
Python function is defined using a keyword def
followed by the name of the function and parentheses. Inside parentheses, you define zero or more arguments.
Arguments (also called parameters) are inputs that are used inside the function to perform a specific task.
Let’s show an example of a simple Python function:
def subtract(a, b):
result = a - b
return result
In this example, we defined a function with the name ‘subtract’. That function takes two arguments ‘a’ and ‘b’. Then function subtracts those numbers and saves the result to a variable named result. In the last line, the function returns the result.
As you can see the code for the function goes inside a block indented under the definition line.
How to call a Python function?
Once you have defined a function, you call it by its name and pass the required arguments in the parentheses:
var result = subtract(10, 5)
print(result) #it would print 5
Keep in mind that you need to pass the arguments in the same order as in the definition of the function.
Otherwise, you will get an error or unwanted result.
Same function with different order of passed arguments:
var result = subtract(5, 10)
print(result) #it would print -5
Default values for arguments
Python functions also enable you to define a default value for each argument.
That way you can call the function without passing that argument and the function will use the default value instead.
For example:
def say_hi(name='user'):
return "Hi " + name
sayHi("Joe") #function will return "Hi Joe"
sayHi() #function will return "Hi user"
In this example, the function ‘say_hi’ takes one argument ‘name’.
That argument has the default value of ‘user’.
This function can be called by passing an argument and it will use that value. Also, this function can be called without an argument and it will use the value ‘user’ instead.
Simple quiz game
In this part of the post, we will use the knowledge about Python functions from above and create a simple quiz game.
The quiz game will ask the user multiple questions and keep track of their score.
First, we'll need to define a list of questions and a list of answers. Here's an example:
questions = ["What is the capital of France?","What is the capital of Italy?","What is the capital of Spain?","What is the capital of Germany?"]
answers = ["Paris","Rome","Madrid","Berlin"]
Next, we'll need to use a loop to iterate through the questions and ask the user for an answer. Here's how to do that:
score = 0
for i in range(len(questions)):
question = questions[i]
answer = answers[i]
user_answer = input(question)
if user_answer == answer:
print("Correct!")
score += 1
else:
print("Incorrect. The correct answer is:", answer)
print("Your score is:", score)
This code will ask the user each of the questions in the questions
list and check if their answer is correct by comparing it to the corresponding answer in the answers
list.
If the user's answer is correct, it will print "Correct!", and if it is incorrect, it will print "Incorrect" and show the correct answer.
After asking all questions, it will print how many correct answers the player had.
Now let’s introduce Python functions and make this code more readable.
First, let’s create a function that will ask a question, take the user’s answer and compare it with the actual answer.
We also called .lower()
function for the user’s answer and actual answer so we can ignore casing. If we did not do that, the function would return ‘False’ if the user for example typed ‘pARis’.
The function will return ‘True’ if the user answered right and ‘False’ otherwise.
def ask_question_and_check_answer(question, answer):
"""Asks the user a question and returns True if their answer is correct, False otherwise."""
user_answer = input(question)
user_answer = user_answer.lower()
return user_answer == answer.lower()
For the rest of the code, let’s create a new function that will call ask_question_and_check_answer
function.
def run_quiz(questions, answers):
"""Runs a quiz game with the given questions and answers."""
score = 0
for i in range(len(questions)):
question = questions[i]
answer = answers[i]
if ask_question_and_check_answer(question, answer):
print("Correct!")
score += 1
else:
print("Incorrect. The correct answer is:", answer)
return score
run_quiz function
takes a list of questions and a list of answers as input, and uses the ask_question_and_check_answer
function to ask the user each of the questions.
It keeps track of the user's score and returns the final score when the quiz is finished.
Let’s also write a function that will print the quiz result:
def pretty_print_results(score, total):
"""Prints the final results of the quiz game."""
print("You scored", score, "out of", total)
if score == total:
print("Congratulations! You got a perfect score!")
elif score / total >= 0.75:
print("Congratulations! You passed with a high score.")
else:
print("Unfortunately, you did not pass. Better luck next time.")
pretty_print_results
takes a score and a total as input, and prints the final results of the quiz game. You can set parameters for the score any way you like.
And in the end, you just need to call those two functions:
# Run the quiz and print the results
score = run_quiz(questions, answers)
pretty_print_results(score, len(questions))
There you have it. Simple quiz application that is created with three Python functions.
Now you can add more questions and answers or if you want a challenge you can find some quiz API and get questions and answers from there.
The complete solution is hosted on our GitHub. Feel free to download it or fork it and play with it.
Conclusion
In this post, we showed what is Python function, how to define one, and how to call it.
Functions are key elements of programming. They are used in most programming languages.
Understanding how to define and use functions is an important skill for any programmer.
If you have any question or suggestion, feel free to post it in the comments or you can find me on Twitter.
Also if you like the content and want to stay updated on the new content you can subscribe to my newsletter.
You will also get a FREE eBook - "learn programming from zero to your first Python program"
Top comments (0)