Parameters and return values
Pass data in and get results back.
🎬 Video version coming soon — read it now
Functions become truly useful when you can give them data and get results back.
Parameters: data going in
def greet(name):
print(f"Welcome to IT Vizag, {name}!")
greet("Sravani")
greet("Rahul")name is a parameter: a variable that gets its value when the function is called. "Sravani" is the argument you pass in.
Several parameters are separated by commas:
def show_price(item, price):
print(f"{item}: ₹{price}")
show_price("Dosa", 60)return: a result coming out
print only shows a value. return hands the value back to the code that called the function, so you can store it and use it.
def add_gst(amount, rate=0.18):
return amount + amount * rate
price = add_gst(1000)
print(price) # 1180.0
print(add_gst(500) * 2) # 1180.0print vs return: the big beginner confusion
def double_print(n):
print(n * 2)
def double_return(n):
return n * 2
x = double_print(5) # shows 10, but x is None
y = double_return(5) # shows nothing, but y is 10
print(x, y) # None 10A function without return gives back None. Most functions should return, not print. Let the caller decide whether to print, save or calculate further.
return ends the function
def grade(marks):
if marks >= 90:
return "A+"
if marks >= 60:
return "B"
return "C"As soon as a return runs, the function stops. That's why no elif is needed here.
Returning several values
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = stats([12, 40, 33])Python packs them into a tuple and you unpack them, as you learned in the last course.
In one line
Parameters bring data in, return sends a result back, and a function that only prints returns None.
Share with a friend