Python Functions

Define reusable blocks of code.

✍️ 3 exercises + code challenge in this lesson

A function is defined with def and runs when called.

  • Parameters are listed in the parentheses; arguments are the values you pass.
  • Default values: def greet(name="Guest")
  • Keyword arguments: greet(name="Ali")
  • *args collects extra positional arguments into a tuple; **kwargs collects keyword arguments into a dict.
  • return sends a value back; a function without return returns None.

Key Takeaways: Python Functions

Mastering Python Functions helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python Functions Code Example

Python
def greet(name="Guest", greeting="Assalam-o-Alaikum"):
    return f"{greeting}, {name}!"

def total(*prices, discount=0):
    return sum(prices) * (1 - discount)

def profile(**info):
    for key, value in info.items():
        print(f"  {key}: {value}")

print(greet())
print(greet("Sara", greeting="Hello"))
print("Total:", total(1200, 800, 500, discount=0.1))
profile(name="Ali", city="Lahore", role="Developer")
Free sign-in required · Google login available

Python Functions Practice Exercises

Check what you learned in “Python Functions”.

/ 3 solved
Fill in the blank

Define a function.

 greet(name):
✓ Correct! Not quite. Try again.
Multiple choice

What does a function return if it has no return statement?

✓ Correct! Not quite. Try again.
Code challenge

Write a function area(w, h) that returns w * h and print area(4, 5).

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services