Functions
Define functions with def, default and keyword arguments, return values, and the if __name__ == "__main__" guard.
Runs in Zerethon IDE · Python 3.12
Official Python documentation ↗
main.py
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
def main():
print(greet("Ada"))
print(greet("Linus", greeting="Hi"))
low, high, mean = stats([4, 8, 6])
print(low, high, mean)
square = lambda x: x * x
print(square(9))
if __name__ == "__main__":
main()
Output
Hello, Ada! Hi, Linus! 4 8 6.0 81
- A function without
returnreturnsNone. - Returning several values returns a tuple, which you can unpack:
low, high, mean = .... if __name__ == "__main__":runsmain()only when this file is the one being run, not when another file imports it.
Watch out: Never use a mutable default such as def add(item, items=[]): the same list is shared by every call. Use items=None and create the list inside.