Functional Code

Jed Rembold

September 8, 2025

Announcements

  • Homework
    • Problem Set 1 due tonight!
    • Problem Set 2 posted by the end of the day
  • Questions?
    • I’ll be around 2-2:50 and then after 5:15pm until around 6:15
    • Don’t forget you can contact your section leaders to ask questions as well!
    • QUAD Center hours tonight from 4:30pm - 9pm
  • Polling: polling.jedrembold.prof

Shorthand and Multiple Assignments

  • It is very common to want to adjust an existing variable value

    balance = balance + deposit
  • Python gives you a shorter expression to describe this relationship:

    balance += deposit
  • You can do this with any operation (op) following the general form:

    variable op= expression
  • You can name multiple variables at once by separating with commas

    A, B, C = 1, 2, 3
    • All the expressions on the right are computed before being assigned to the left variables
    • This can give you a very concise way of swapping variable values

The Python Repl

  • You may have worked with some tools in the past that utilize an interactive environment
    • Type a command in, press enter, and you get instant feedback
  • Python has this as well, though the basic version is a bit clunky (imho)
  • To access, on a terminal, simply type python (or however you access Python on your system)
    • You will always know you are in the interactive environment by the triple-greater-than prompt: >>>
    • In the interactive environment, you can simply type a variable and press enter to see it displayed
    • To exit, you must type: exit()
  • Writing full programs in the REPL is very cumbersome, but for quick tests, it can be quite useful

Understanding Check

What is the printed value of A in the code below?

>>> A = 10
>>> B = 5 % 3
>>> C = A * B ** B
>>> A -= B + A // 2
>>> A, B, C = C, A, B
>>> A
??
  1. 3
  2. 12
  3. 30
  4. 40

Python Applications

  • In Python, application programs are generally stored in files whose names end with .py. Such files are called modules.
  • Most interesting applications interact with the user
    • In modern applications, this often happens through a graphical user interface or GUI
      • We’ll be constructing some GUIs later this semester!
    • For now, all interaction will happen through the terminal
      • Thus, we need to know how to output information to the terminal, as well as how to input information into the terminal
      • Without this, our programs are not very useful

Output: print

  • We’ve seen how to output the value of a variable from within Python’s REPL, but that won’t work within a program

  • Python’s built-in print() function will display whatever is between the () to the terminal

    >>> A = 10
    >>> print(A)
    10
  • If you want to display several things, separate each thing by a comma inside the print statement. This will insert a space between each when printed.

    >>> print(1,3,5)
    1 3 5

Functions (Extended)

What is your Function?

  • As discussed in the context of Karel, a function is a sequence of commands that have been collected together and given a name.
  • Unlike in Karel though, functions typically go beyond that and can have inputs and outputs
  • At times we are concerned about what happens in the function, but at other times we can treat it as a mysterious “black-box”

Writing your own functions

  • The more general form of a function definition looks like:

    def |||name|||(|||parameters|||):
        |||statements in function body|||
    • |||name||| is your chosen name for the function
    • |||parameters||| is a comma-separated list of variable names that will have each input value assigned to them
  • You can return or output a value from the function by including a return statement in the function body

    return |||some expression|||
    • |||some expression||| is the value you want to return or output
    • If no return statement is included, Python will by default return None

A Functional Diagram

output input function def def cool(a,b): c = a + b return c + a cool(4,5) a 4 b 5 c 9 13

Simple function examples

  • Convert Fahrenheit temperatures to their Celsius equivalent

    def f_to_c(f):
        return 5 / 9 * (f - 32)
    • Using the function:

      print(f_to_c(45))
  • Computes the volume of a cylinder of height h and radius r

    def cylinder_volume(r, h):
        return 3.14159 * r**2 * h
    • Using the function:

      vol1 = cylinder_volume(2,10)
      vol2 = cylinder_volume(10,2)
      print(vol1 + vol2)

Using Functions: Built-ins

  • All modern languages include a collection of pre-defined functions for convenience
  • In Python, common build-in functions that operate on numbers include:
Function Description
abs(x) The absolute value of x
max(x,y,...) The largest of all the arguments
min(x,y,...) The smallest of all the arguments
round(x) The value of x rounded to the nearest integer
int(x) The value of x truncated to an integer
float(x) The value of x as a decimal

Libraries

Visiting the library(ies)

  • A huge strength of Python is that it offers a very large number of code collections called libraries
    • Can save you the effort from writing that code yourself!
  • Requires you to import that library, which can take several different forms
    • Most common is to use import |||lib||| to grab everything in a library

      import math
      • You must then access any function in that library using its fully qualified name, which includes the library name (var = math.sqrt(4))
    • Can also use from |||lib||| import |||function||| to grab specific functions from the library

      from math import sqrt
      • You do not need to use the library name then when you call it (var = sqrt(4))

Useful math definitions

Code Description
math.pi The mathematical constant \(\pi\)
math.e The mathematical constant \(e\)
math.sqrt(x) The square root of x
math.log(x) The natural logarithm of x
math.log10(x) The base 10 logarithm of x
math.sin(x) The sine of x in radians
math.cos(x) The cosine of x in radians
math.asin(x) The arcsin of x
math.degrees(x) Converts from radians to degrees
math.radians(x) Converts from degrees to radians

Python’s Path

  • Wherever possible, Python runs code one line at a time, from top to bottom

  • It will not, however, enter indented blocks unless it has to

    • The code inside a function definition, for example, is only run when the function is called
  • A common paradigm then is to define functions first, and then include the code to run those functions beneath

    def func1(a):
        return a + 1
    
    def func2(b):
        return b // 2
    
    print(func1(2) + func2(2))

Collections on Constants and Functions

  • A library should generally just be a collection of defined functions and constants
    • You don’t want any code to actually run when you import the library, you just want to access the desired pieces
  • If you place everything inside a function definition though, nothing actually happens when you run the library code!
    • You just defined a bunch of functions, but never did anything with them
  • Commonly, we want the best of both worlds:
    • I can use a program easily as a library, if I want to import a defined function
    • I can run the program directly and have something actually happen

Running a Program

  • Karel programs always run the first defined function in the code when the program was run. General Python programs do not follow the same convention.

  • Python programs need to specify what part of the code is supposed to be executed when a program is run if everything is just function definitions. This commonly happens at the bottom of the program:

    if __name__ == '__main__':
        |||function_to_run()|||
    • |||function_to_run||| is the name of whatever function you want to execute when the program is run directly
  • Patterns of this sort are commonly called boilerplate

    • Less important to fully understand all the pieces of it now
    • Is important to understand what it is doing and how to implement it correctly

Sample Program

def print_odds(des_num):
    """
    Prints the first desired number of odd numbers 
    starting from 1.
    """
    value = 1
    for i in range(des_num):
        print(value)
        value += 2

if __name__ == '__main__':
    print_odds(100)

Practice

  • Most people have seen or had to memorize the quadratic formula at some point in time. As a reminder, the equation \[a\cdot x^2 + b\cdot x + c = 0\] can be solved for \(x\) according to \[x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \]
  • Take some time with a neighbor to work out how you could define a function quad which takes 3 arguments a,b,c and returns the greater of the two solutions (the \(+\) one)
    • Tip: writing out complicated equation on a single line in Python can get real ugly and hard to understand. Consider breaking up the equation and assigning pieces of it to variables that you can combine later.
// reveal.js plugins