Lesson 8 of 40Article16 min
Functions & User Input
Define functions with def name():. Use parameters, default values, and return to send results back.
Python Functions
Define functions with def name():. Use parameters, default values, and return to send results back.
Keep functions small and focused on one job.
Real-life example: A function is a coffee machine button — press once, same steps run every time.
Function with return
def greet(name, role="student"):
return f"Hello {name}, you are a {role}."
print(greet("Meera"))
print(greet("Carlos", "instructor"))Python User Input
input() reads text from the keyboard. Always returns a string — cast to int/float when needed.
Validate input and handle errors with try/except for robust CLI apps.
Real-life example: input() is a waiter asking your order — you speak, Python writes it down as text.
Safe numeric input
raw = input("Enter your age: ")
try:
age = int(raw)
print(f"Next year you will be {age + 1}.")
except ValueError:
print("Please enter a valid number.")