15 Levels Of Writing Python Functions

1) Basic functions with 0 arguments

def hello():
    print('hello')
    print('world')

hello()

# hello
# world

The absolute most basic function you can write — a function that takes in 0 arguments, but does only one uncustomizable thing.

2) Functions that take in 1 argument

def add10(n):
    return n + 10

print(add10(4))    # 14
print(add10(5))    # 15

Here, our function takes in one and only one argument, and adds 10 to it.

3) Functions that take in 2 or more arguments

def add(a, b):
    return a + b

print(add(10, 4))      # 14
print(add(100, 5))     # 105
def average(a, b, c):
    return (a+b+c)/3

print(average(1,2,3))    # 2.0
print(average(3,4,6))    # 4.333333333

We can make functions take in as many arguments as we want them to.

4) Functions with default/optional parameters

We can make our functions take in default parameters, also known as optional parameters.

def greet(name, greeting='hello'):
    print(greeting, name)

greet('tim', 'hola')      # hola tim
greet('tim')              # hello tim

Here, greeting is a default parameter/optional parameter.

  • If we don’t pass in anything, greeting defaults to 'hello'
  • If we pass in something, greeting takes that value

Visit Now https://levelup.gitconnected.com/15-levels-of-writing-python-functions-77f48c3a4f8b