Python Functions Tutorial - def, return, scope, keyword arguments | Beginner #11
Video: Python Functions Tutorial - def, return, scope, keyword arguments | Beginner #11 by Taught by Celeste AI - AI Coding Coach
Watch full page →Python Functions Tutorial: def, return, scope, and Keyword Arguments
This tutorial covers the fundamentals of Python functions, including how to define and call them, use return values, and manage parameter scope. You'll also learn about default and keyword arguments, docstrings, and how to handle multiple return values with tuples. A mini project demonstrates these concepts by building a grade calculator using multiple functions.
Code
def greet(name="Guest"):
"""Return a greeting message for the given name."""
return f"Hello, {name}!"
def calculate_average(*scores):
"""Calculate the average of given scores."""
total = sum(scores)
count = len(scores)
return total / count if count else 0
def grade_calculator(score):
"""Return letter grade based on numeric score."""
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
def main():
# Using keyword argument
print(greet(name="Alice"))
print(greet()) # uses default parameter
# Multiple scores passed as positional arguments
avg = calculate_average(88, 92, 79, 93)
print(f"Average score: {avg:.2f}")
# Get letter grade from average
letter = grade_calculator(avg)
print(f"Letter grade: {letter}")
# Accessing docstring
print(grade_calculator.__doc__)
# Variable scope example
global_var = 10
def modify_global():
global global_var
global_var = 20 # modifies the global variable
print(f"Before modify_global: {global_var}")
modify_global()
print(f"After modify_global: {global_var}")
if __name__ == "__main__":
main()
Key Points
- Functions are defined using
defand can have default parameter values and keyword arguments. - Return statements send values back to the caller; functions can return multiple values using tuples.
- Docstrings provide documentation accessible via the
__doc__attribute. - Variables defined inside functions are local by default; use the
globalkeyword to modify global variables. - Functions help organize code and enable reuse, demonstrated here with a grade calculator example.