Python 3

home

Introduction to Python

davidbpython.com




More About User-Defined Functions


user-defined functions and code organization

User-defined functions help us organize our code -- and our thinking.


Let's now return to functions from the point of view of code organization. Functions are useful because they:






review: function block, argument and return value

def add(val1, val2):
    mysum = val1 + val2
    return mysum

a = add(5, 10)      # int, 15

b = add(0.2, 0.2)   # float, 0.4

Review what we've learned about functions:


Ex. 12.1 - 12.4






functions without a return statement return None

When a function does not return anything, it returns None.


def do(arg):
    print(f'{arg} doubled is {arg * 2}')
    # no return statement returns None

x = do(5)        # (prints '5 doubled is 10')

print(x)         # None


Actually, since do() does not return anything useful, then we should not call it with an assignment (i.e., x = above), because no useful value will be returned. If you should call a function and find that its return value is None, it often means that it was not meant to be assigned because there is no useful return value. Ex. 12.5 - 12.6






the None object type

The None value is the "value that means 'no value".


zz = None

print(zz)        # None
print(type(zz))  # <class 'NoneType'>

aa = 'None'      # oops, this is a string -- not the None value!






function argument type: positional

Positional arguments are required to be passed, and assigned by position.


def greet(firstname, lastname):
    print(f"Hello, {firstname} {lastname}!")

greet('Joe', 'Wilson')   # passed two arguments:  correct

greet('Marie')           # TypeError: greet() missing 1 required positional argument: 'lastname'






function argument type: keyword

Keyword args are not required, and if not passed return a default value.


def greet(lastname, firstname='Citizen'):
    print(f"Hello, {firstname} {lastname}!")

greet('Kim', firstname='Joe')   # Hello, Joe Kim!

greet('Kim')                    # Hello, Citizen Kim!


12.7 - 12.8





[pr]