Python Functions

Python Functions

Python Functions

Functions are reusable pieces of programs. They allow you to give a name to a block of statements, then you can run that block using the specified name anywhere in your program and any number of times.

Python Functions

You're Already Using Functions!

>> print('Hello, world!')
None

>> input("Enter your name: ")
None

>> int("42")
42

>> randint(1, 10)
7
Python Functions

Defining a Function

  • Use the def keyword followed by the function name and parentheses.
  • Example:
    def say_hello():
        print('Hello, world!')
    
Python Functions

Function Arguments

You can provide arguments to a function, which act as inputs.

def print_max(a, b):
    if a > b:
        print(a, 'is maximum')
    else:
        print(b, 'is maximum')

Call the function with arguments:

print_max(3, 4)
Python Functions

The return Statement

The return statement is used to return a value from a function.

def maximum(x, y):
    if x > y:
        return x
    else:
        return y

Call the function

print(maximum(2, 3))
Python Functions

Exercise

Go back to your Calculator program from the beginning of class and refactor it to use functions.

The function arguments should be the two numbers and the operation to perform.

Python Functions

Keyword Arguments

  • Positional Arguments: The order of arguments is important.
    print_max(3, 4)
    
  • Keyword Arguments: The order of arguments is not important.
    print_max(b=3, a=4)
    
Python Functions

Default Arguments

  • Keyword Default Arguments: Keyword arguments can have default values.
    def say(message, times=1):
        print(message * times)
    
    say('Hello')    # => 'Hello'
    say('World', 5) # => 'WorldWorldWorldWorldWorld'
    
Python Functions

Local Variables

Variables defined within a function are local to that function.

def func(x):
    print('x is', x)
    x = 2
    print('Changed local x to', x)

Call the function:

x = 50
func(x)
print('x is still', x)
Python Functions

Recursion

A function can call itself. This is known as recursion.

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)
Python Functions

Docstrings

You can add documentation to functions using docstrings.

def print_max(a, b):
    """
    Prints the maximum of two numbers.
    """
    a = int(a)  # Convert to integers, if possible
    b = int(b)
    if a > b:
        print(a, 'is maximum')
    else:
        print(b, 'is maximum')
Python Functions

Accessing Docstrings

>>> print(print_max.__doc__)
Prints the maximum of two numbers.

>>> help(print_max)
print_max(a, b)
    Prints the maximum of two numbers.
Python Functions

Type Hints

These are unecessary but nice to have, especially in Google Colab.

def print_max(a: int, b: int):
    '''Prints the maximum of two numbers.'''
    if a > b:
        print(a, 'is maximum')
    else:
        print(b, 'is maximum')

print_max(3, "4") # Incorrect type!!!
Python Functions

Python Functions

Summary

  • Functions are reusable blocks of code.
  • Use def to define functions.
  • Functions can have parameters and return values.
  • Local variables are confined to the function scope.
  • Document your functions with docstrings for better readability.
Python Functions

Exercise

http://gg.gg/1b81yy

TODO: This exercise was hard to implement in class. Come up with something better next time.

TODO: We should just skip this

TODO: This was WAAAAY too hard for a first assignment. Should have started with is_prime or literally anything else.