Welcome back. If you followed the QBasic series, this one will feel familiar from a different
angle, remember SUB and FUNCTION? Python only has one word for both ideas, function, whether it just does
something or hands back a value depends entirely on whether you write a return line inside it.
What's in this post
- Why bother with functions at all
- Defining a function with def
- return, giving a value back
- Default parameter values
- The function machine (try it!)
- Scope, what happens inside stays inside
- Example 1 (Easy): A greeting function
- Example 2 (Medium): A function that returns a value
- Example 3 (Harder): Default parameters in action
- Example 4 (Hero level): Functions calling functions
- Common mistakes
- Practice tasks
1. Why bother with functions at all
2. Defining a function with def
def greet(name):
print("Namaste, " + name + "!")
greet("Diwakar")
greet("Sapana")
name here is a parameter, a placeholder waiting for a real value. "Diwakar"
and "Sapana" are the actual arguments we hand it each time we call the function.
3. return, giving a value back
def square(n):
return n * n
result = square(5)
print(result) # 25
4. Default parameter values
You can give a parameter a fallback value, used only when the caller doesn't supply one.
def greet(name="friend"):
print("Namaste, " + name + "!")
greet("Diwakar") # Namaste, Diwakar!
greet() # Namaste, friend!
5. The function machine
Try it: pick a function, send a number through it
Same number, different function, different answer. That's the whole point of writing them separately.
def square(n):
return n * n
6. Scope, what happens inside stays inside
def square(n):
result = n * n
return result
print(square(4))
print(result) # NameError: result only exists inside square()
7. Example 1 (Easy): A greeting function
def greet(name):
print("Welcome, " + name + "!")
greet("Rojina")
greet("Bikash")
8. Example 2 (Medium): A function that returns a value
def is_even(n):
return n % 2 == 0
num = int(input("Enter a number: "))
if is_even(num):
print("Even")
else:
print("Odd")
is_even(n) directly returns True or False, which is exactly what an if
needs, no extra comparison required.
9. Example 3 (Harder): Default parameters in action
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25, uses default exponent
print(power(5, 3)) # 125, overrides it
10. Example 4 (Hero level): Functions calling functions
def grade(marks):
if marks >= 90:
return "A+"
elif marks >= 75:
return "A"
elif marks >= 60:
return "B"
elif marks >= 40:
return "C"
else:
return "Fail"
def report(names, marks_list):
for i in range(len(names)):
g = grade(marks_list[i])
print(f"{names[i]} scored {marks_list[i]} -> Grade {g}")
names = ["Sunita", "Ramesh", "Anita"]
marks = [78, 55, 92]
report(names, marks)
report() calls grade() once for every student, inside its own loop.
This is exactly what the QBasic FUNCTION Grade$ example did in Post 10 of that series, write the rule once, call it
as many times as needed.
11. Common mistakes
- Forgetting return, and being confused when the function gives back None.
- Using print() where you actually needed return, print only shows something, it doesn't hand the value anywhere else in your program.
- Trying to use a variable from inside a function, outside it, that's the scope rule from section 6.
- Calling a function with the wrong number of arguments. If def expects two parameters, you generally need to supply two, unless defaults are involved.
12. Practice tasks
- Write a function
cube(n)that returns n raised to the power of 3. - Write a function
is_vowel(letter)that returns True if the letter is a vowel. - Write a function
greet(name, greeting="Namaste")with a default greeting, then call it both with and without the second argument. - Challenge: write a function
max_of_three(a, b, c)that returns the largest of three numbers, without using Python's built-in max().
Functions are really the first proper step toward organizing real programs instead of writing one long script top to bottom. Next in the rotation, we're back to DBMS for Part 5, where we finally connect two tables together with JOINs. After that, Python Part 7, reading and writing files.
— Diwakar
Comments