CSci 150: Foundations of computer science
Home Syllabus Readings Projects Tests

Functions & strings


You'd be familiar with functions in mathematics, like f(x). A function in Python is similar: You use the function by giving the function name followed by some arguments listed in parentheses, and the function computes a result called the return value.

smaller = min(xy)

In this example, we pass the current values of x and y as our arguments to the function named min. As it happens, min returns the minimum value among its arguments, which this example saves into its smaller variable.

You can use functions wherever you would like within an expression. The following example uses max to compute the largest among three different values and min to compute the smallest; the difference between the results is saved into the range variable.

range = max(xyz) - min(xyz)

For now, I'd like to highlight four numeric functions.

abs(x)the absolute value of x
max(xy)the maximum of x and y
min(xy)the minimum of x and y
round(x)the result of rounding x to the nearest integer


In addition to numeric values, Python programs can also deal with strings — character sequences like words or sentences. These will prove important as we write programs that interact with the user (reading and displying text) and that process files (which often store data as character sequences).

Creating a particular string is easy: Just enclose it in quotes.

name = 'Python'

You can use either double quotes or single quotes, as long as both sides match. Most use single quotes unless the string has single quotes in it.

sentence = "I'm catching on"

The quotes are necessary, though. If you type “name = Python”, the computer will assume that you mean to copy value of the variable Python into name. To mention the specific character sequence P-y-t-h-o-n, you need to enclose it in quotes.

String operations

To start working with strings, here are four things you can do to them: