livepython.net
CHAPTER 15Python Functions
15.5  PRACTICE

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 writeIt 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 + bhands a value back; the call becomes that value
print() vs returnprint shows a value to a person; return gives it to your code
a function with no returngives back None
a variable made inside a functionlocal: it's gone once the function ends
a variable made outside every functionglobal: 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

  1. 130.Python Program to Print a Welcome Banner Using a FunctionEasySolve
  2. 131.Python Program to Draw a Box Using FunctionsMediumSolve

Parameters and arguments

  1. 132.Python Program to Find the Area and Perimeter Using a FunctionEasySolve
  2. 133.Python Program to Calculate a Bill with a Default TipMediumSolve
  3. 134.Python Program to Print a Triangle Using a Function with ParametersMediumSolve

The return statement

  1. 135.Python Program to Convert Celsius to Fahrenheit Using a FunctionEasySolve
  2. 136.Python Program to Find the Largest of Three Numbers Using a FunctionMediumSolve
  3. 137.Python Program to Check a Prime Number Using a FunctionMediumSolve

Scope, docstrings and good habits

  1. 138.Fix the NameError in a Python FunctionEasySolve
  2. 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.