Practice: Introduction to Functions

« Read the chapter

Q1. Hello function

BeginnerCoding

Define a function say_hello that prints Hello, world! and call it once.

Goal: Define and call a function.

Q2. Call twice

BeginnerCoding

Define a function line that prints ten dashes. Call it twice.

Goal: Reuse a function.

Q3. Greeting with name

BeginnerCoding

Define greet(name) that prints Hi followed by the name. Call it with Asha.

Goal: Pass a value to a function.

Q4. Double a number

BeginnerCoding

Define double(n) that returns n times 2. Print double(21).

Goal: Use return.

Q5. Rectangle area

IntermediateCoding

Define area(w, h) that returns width times height. Print area(4, 5).

Goal: Write a function with two parameters.

Q6. Banner

IntermediateCoding

Define banner() that prints a line of stars, the word MENU, and another line of stars (5 stars). Call it.

Goal: Group statements in a function.

Q7. Order of prints

BeginnerOutput

Predict the output.

Code
def hi():
    print("hi")

print("start")
hi()
print("end")

Goal: Trace function calls.

Q8. Defined but not called

BeginnerOutput

Predict the output.

Code
def hi():
    print("hi")

print("only this")

Goal: Understand def versus call.

Q9. Return value

BeginnerOutput

Predict the output.

Code
def add(a, b):
    return a + b

print(add(2, 3))

Goal: Read a return.

Q10. Called twice

IntermediateOutput

Predict the output.

Code
def tick():
    print("tick")

tick()
tick()
tick()

Goal: Count function calls.

Q11. Nested calls

IntermediateOutput

Predict the output.

Code
def sq(n):
    return n * n

print(sq(sq(2)))

Goal: Use a call as an argument.

Q12. No return

IntermediateOutput

Predict the output.

Code
def f():
    x = 5

print(f())

Goal: Know the default return value.

Q13. Fix the missing colon

BeginnerDebugging

This code gives a SyntaxError. Fix it.

Code
def hello()
    print("hello")

hello()

Goal: Spot syntax errors in def.

Q14. Fix the call

BeginnerDebugging

Nothing prints. Fix the program so it prints hello.

Code
def hello():
    print("hello")

hello

Goal: Call with brackets.

Q15. Why use functions?

BeginnerConceptual

Give two reasons why programmers write functions.

Goal: State the benefits of functions.

Q16. Discount helper

IntermediateApplication

A shop applies a 10 percent discount in many places. Write discount(price) that returns the discounted price and print discount(200).

Goal: Apply a function to a real task.