Practice: Introduction to Functions
Q1. Hello function
Define a function say_hello that prints Hello, world! and call it once.
Goal: Define and call a function.
Q2. Call twice
Define a function line that prints ten dashes. Call it twice.
Goal: Reuse a function.
Q3. Greeting with name
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
Define double(n) that returns n times 2. Print double(21).
Goal: Use return.
Q5. Rectangle area
Define area(w, h) that returns width times height. Print area(4, 5).
Goal: Write a function with two parameters.
Q6. Banner
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
Predict the output.
def hi():
print("hi")
print("start")
hi()
print("end")Goal: Trace function calls.
Q8. Defined but not called
Predict the output.
def hi():
print("hi")
print("only this")Goal: Understand def versus call.
Q9. Return value
Predict the output.
def add(a, b):
return a + b
print(add(2, 3))Goal: Read a return.
Q10. Called twice
Predict the output.
def tick():
print("tick")
tick()
tick()
tick()Goal: Count function calls.
Q11. Nested calls
Predict the output.
def sq(n):
return n * n
print(sq(sq(2)))Goal: Use a call as an argument.
Q12. No return
Predict the output.
def f():
x = 5
print(f())Goal: Know the default return value.
Q13. Fix the missing colon
This code gives a SyntaxError. Fix it.
def hello()
print("hello")
hello()Goal: Spot syntax errors in def.
Q14. Fix the call
Nothing prints. Fix the program so it prints hello.
def hello():
print("hello")
helloGoal: Call with brackets.
Q15. Why use functions?
Give two reasons why programmers write functions.
Goal: State the benefits of functions.
Q16. Discount helper
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.