Python Functions Practice Questions for Beginners
Chapter 15 Recap and Practice
You can now build your own functions. Here is the chapter in one table:
| You write | It does |
|---|---|
def greet(): | defines a function: a name, brackets, a colon, then an indented body |
greet() | calls it: runs the body. Define first, then call |
def greet(name): | name is a parameter: a blank the call fills in |
greet("Sunny") | "Sunny" is an argument: the value for the parameter |
introduce("Sunny", 25) | positional arguments: matched in order |
introduce(age=25, name="Sunny") | keyword arguments: matched by name, any order |
def greet(name, greeting="Hello"): | a default value makes a parameter optional; defaults go last |
return a + b | hands a value back; the call becomes that value |
print() vs return | print shows a value to a person; return gives it to your code |
a function with no return | gives back None |
| a variable made inside a function | local: it's gone once the function ends |
| a variable made outside every function | global: functions can read it, but assigning makes a new local |
"""Return the area.""" | a docstring: the first line of the body, saying what the function does |
And the habits: one job per function, a verb name, values in as arguments, answers out with return.
Practice questions
Write each program with at least one function, and call it with the values you read. Use input() with no prompt text. The tests try several inputs, so test your program with a few of your own too.
Define and call functions
- 130.Python Program to Print a Welcome Banner Using a FunctionEasySolve
- 131.Python Program to Draw a Box Using FunctionsMediumSolve
Parameters and arguments
- 132.Python Program to Find the Area and Perimeter Using a FunctionEasySolve
- 133.Python Program to Calculate a Bill with a Default TipMediumSolve
- 134.Python Program to Print a Triangle Using a Function with ParametersMediumSolve
The return statement
- 135.Python Program to Convert Celsius to Fahrenheit Using a FunctionEasySolve
- 136.Python Program to Find the Largest of Three Numbers Using a FunctionMediumSolve
- 137.Python Program to Check a Prime Number Using a FunctionMediumSolve
Scope, docstrings and good habits
- 138.Fix the NameError in a Python FunctionEasySolve
- 139.Python Program to Make a Marks Report Using FunctionsHardSolve
Functions turn long programs into small, named, reusable steps. Next, you'll learn PEP 8: how to style your code so it's easy for everyone to read.