Practical Coding in Python

Learn to write and validate your own code

Darren Kessner, PhD

(revised September 1, 2025)

Previous: 1. Functions and Testing

Functions

#
# functions.py
#


def hello():
    print("Hello, world!")

hello()

# Difference from Java: note the lack of type specifications in
# either input parameters or return values

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

print("sum(5,7):", sum(5,7))

# dynamic typing: for strings, + is concatenation
print(sum("Hello, ", "world!")) 


def is_odd(n):
    return n%2 == 1

print("is_odd(5):", is_odd(5))
print("is_odd(7):", is_odd(7))
print("is_odd(8):", is_odd(8))


# Python has a very useful feature called List Comprehensions.

odd_numbers = [i for i in range(10) if is_odd(i)]
print("odd_numbers:", odd_numbers)

even_numbers = [2*i for i in range(5)]
print("even_numbers:", even_numbers)


# In general, you can write:
# my_list = [f(x) for x in things if P(x)]
#
# You can think of P() as a condition that gives you a subset of
# things, and f() is a transformation of each thing x.

Output:

Hello, world!
sum(5,7): 12
Hello, world!
is_odd(5): True
is_odd(7): True
is_odd(8): False
odd_numbers: [1, 3, 5, 7, 9]
even_numbers: [0, 2, 4, 6, 8]

Next: