Functions are defined with def. They accept parameters and can return values with return:
def greet(name, hour=12):
if hour < 12:
return f"Good morning, {name}!"
elif hour < 18:
return f"Good afternoon, {name}!"
else:
return f"Good evening, {name}!"
print(greet("Alice")) # Good afternoon, Alice!
print(greet("Bob", 8)) # Good morning, Bob!
print(greet("Carol", 20)) # Good evening, Carol!
Here hour has a default value (12) — if not provided, Python uses it.
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 7, 2, 9])
print(low, high) # 1 9
Write a function is_prime(n) that returns True if n is a prime number, otherwise False.
A prime number is divisible only by 1 and itself. 2, 3, 5, 7, 11 are primes. 1 is not.
Click "Run" to execute your code.