» Quick Introduction to Python » 1. Basics » 1.9 Functions

Functions

Define a Function

def multiply(s, times):
    return s * times

# with type annotations
def multiply(s: str, times: int) -> str:
    return s * times

# with default value for parameters
def multiply2(s: str, times: int = 2) -> str:
    return s * times

Check here for more about type annotations: https://peps.python.org/pep-0484/

Call the Function

s = multiply("literank.com", 3)
print(s) # literank.comliterank.comliterank.com

print(multiply2("literank")) # literankliterank

Arbitrary Arguments

def total(*args):
    t = 0
    for arg in args:
        t += arg
    return t

print(total(1, 2, 3)) # 6
print(total(1, 2, 3, 4, 5, 6)) # 21

Keyword Arguments

def list_items(**kwargs):
    for kw in kwargs:
        print(kw, '->', kwargs[kw])

list_items(alice=4, bob=8, cindy=9, douglas=10) # alice -> 4, bob -> 8 ...

Return Multiple Values

def swap(x: int, y: int) -> (int, int):
    return y, x

a, b = 10, 20
c, d = swap(a, b)
print(c, d) # 20, 10

Inner Function

def outer():
    def inner():
        print("inner")
    
    print("outer begins")
    inner()
    print("outer ends")

outer()

Lambda Function

plus_three = lambda a: a + 3

print(plus_three(2)) # 5

# use lambda function as a argument
l = [(1, 2), [5, 1], [8,9]]
print(l) # [(1, 2), [5, 1], [8, 9]]
l.sort(key=lambda a: a[1]) # sort by the second child of the element
print(l) # [[5, 1], (1, 2), [8, 9]]

Code Challenge

Try to modify the code provided in the editor to sort the records in descending order by the quiz score.

Loading...
> code result goes here
Prev
Next