Functions

Functions: Introduction

In mathematics, a function maps inputs to outputs.

For example:

\[f(x, y) = x + y\]

This function takes two inputs, x and y, and produces one output.

\[z = f(x, y) = x + y\]

In programming, functions are reusable commands that perform specific tasks.

Some functions display information. Some functions transform values. Some functions ask the user for information. Some functions return information that we can store in a variable.

We have already used one function many times:

print("Hello world")
Hello world

print() is a function. It receives an input and displays it on the screen.


Built-in Functions in Python

Python includes many ready-made functions. These are called built-in functions.

Some useful built-in functions are:

Function What it does
print() Displays something on the screen
type() Returns the type of a value
int() Converts a value to an integer
float() Converts a value to a decimal number
round() Rounds a number
abs() Returns the absolute value
str() Converts a value to a string
len() Returns the length of something
input() Asks the user for information

The type() Function

The type() function tells us the type of a value.

x = 10
print(f"x is a {type(x)}")

y = 2.72
print("y is a", type(y))

s = "Hello world"
print("s is a", type(s))

print(type(False))
print(type(print))
x is a <class 'int'>
y is a <class 'float'>
s is a <class 'str'>
<class 'bool'>
<class 'builtin_function_or_method'>

Notice that type(print) also works. In Python, functions are objects too.

Exercise

Without running the code, what will Python print?

x = "10"
y = 10

print(type(x))
print(type(y))
<class 'str'>
<class 'int'>

x is a string because it is written inside quotation marks. y is an integer.


Type Conversion

Sometimes a value has the wrong type.

For example, "12" looks like a number, but Python sees it as text.

x = "12"

print(type(x))
print(x * 2)
<class 'str'>
1212

Because x is a string, x * 2 repeats the text.

To use it as a number, we must convert it.


The int() Function

int(x) converts a value to an integer.

pi = 3.1415

print("pi is a", type(pi))

pi_new = int(pi)

print(f"We converted {pi} to {pi_new}")
print("pi_new is a", type(pi_new))
pi is a <class 'float'>
We converted 3.1415 to 3
pi_new is a <class 'int'>

Be careful: int() does not round to the closest integer. It removes the decimal part.

x = 5.9999

print(f"Input number:   {x}")
print(f"Using f-string: {x:.0f}")
print(f"Using int:      {int(x)}")
Input number:   5.9999
Using f-string: 6
Using int:      5

With negative numbers, int() truncates toward zero.

print(int(5.9))
print(int(-5.9))
5
-5

int() can convert strings that contain whole numbers.

x = "12"
y = int(x)

print(y * 2)
24

But int() fails when the input contains anything other than a whole number.

s = "Hello"

print(int(s))
ValueError: invalid literal for int() with base 10: 'Hello'

This also fails:

s = "3.14"

print(int(s))
ValueError: invalid literal for int() with base 10: '3.14'

Even though "3.14" looks numeric, it is not written as an integer.


The float() Function

float(x) converts a value to a decimal number.

Unlike int(), float() accepts strings with decimal points.

s = "3.14"

print(s)
print(type(s))

new_s = float(s)

print(new_s)
print(type(new_s))
3.14
<class 'str'>
3.14
<class 'float'>

But float() cannot understand operations written as strings.

s = "5 / 2"

print(float(s))
ValueError: could not convert string to float: '5 / 2'

Python sees "5 / 2" as text, not as a calculation.

Exercise

Which of these lines will work?

print(float("4.5"))
print(float("4"))
print(float("four"))
print(float("4,5"))

These work:

print(float("4.5"))
print(float("4"))

These fail:

print(float("four"))
print(float("4,5"))

Python uses . as the decimal point, not ,.


The round() Function

round(x, decimals) rounds a numeric value to a given number of decimal places.

x = round(3.1415, 2)

print(x)
3.14

The number of decimals can be 0, but the output is still a floating-point number.

x = 5.9999

print(f"Input number:   {x}")
print(f"Using f-string: {x:.0f}")
print(f"Using int:      {int(x)}")
print(f"Using round:    {round(x, 0)}")
Input number:   5.9999
Using f-string: 6
Using int:      5
Using round:    6.0
Exercise

Predict the output.

price = 19.987

print(round(price, 2))
print(round(price, 1))
print(round(price, 0))
19.99
20.0
20.0

The abs() Function

abs(x) returns the absolute value of x.

x = abs(-5)

print(x)
5

This is useful when we care about distance from zero.

temperature_change = -7

print(abs(temperature_change))
7
Exercise

A city was at 3 degrees in the morning and -4 degrees at night.

Write code that calculates the size of the temperature change.

morning = 3
night = -4

change = night - morning

print(abs(change))
7

The str() Function

str(x) converts a value to a string.

x = 10

print(type(x))

s = str(x)

print(type(s))
<class 'int'>
<class 'str'>

This is useful when we want to combine numbers with text.

age = 25

message = "I am " + str(age) + " years old"

print(message)
I am 25 years old

With f-strings, Python does this conversion for us.

age = 25

message = f"I am {age} years old"

print(message)
I am 25 years old

The len() Function

len(x) returns the length of a sequence.

For now, we will use it with strings.

print(len("a b"))
3

Spaces count.

In the example above:

  • "a" is character 1
  • " " is character 2
  • "b" is character 3

So len("a b") returns 3.

print(len("There is fun in functions"))
25

len() can also help us count the number of digits in a number.

x = 76875675474657

print(len(str(x)))
14

First, str(x) converts the number into text. Then, len() counts how many characters that text contains.

Exercise

Write code that counts how many digits there are in the number below.

number = 90000012345
number = 90000012345

digits = len(str(number))

print(digits)
11

Combining Functions

Functions can be used inside other functions.

x = "3.14"

print(type(float(x)))
<class 'float'>

Python evaluates the inner function first:

  1. float(x) converts "3.14" to 3.14
  2. type(...) checks the type
  3. print(...) displays the result

Another example:

number = 123456

print(len(str(number)))
6
Exercise

Without running the code, what is the output?

x = "100"

print(type(x))
print(type(int(x)))
print(int(x) + 50)
<class 'str'>
<class 'int'>
150

The input() Function

The input(message) function collects data from the user.

It pauses the program and waits for the user to type something.

x = input("Give me a number: ")

print(f"Your number is {x}")

input() always returns a string.

x = input("Give me a number: ")

print(type(x))

So if we want a number, we must convert it.

number = input("Give me a number: ")

number = int(number)

if number % 2 == 0:
    print("Your number is even")
else:
    print("Your number has odd parity")

We can also convert the input directly.

number = int(input("Give me a number: "))

if number % 2 == 0:
    print("Your number is even")
else:
    print("Your number has odd parity")
Exercise

Without running the code, what will the program print if the user enters 5?

x = int(input("Give me a number: "))

print(x * 8)

The program prints:

40

In general, the program prints the user input multiplied by 8.

We can use several input() statements in the same code.

x = float(input("Give me a number:       "))
y = float(input("Give me another number: "))

print(f"{x:.0f} x {y:.0f} = {x * y:.0f}")
Exercise: Simple Calculator

Ask the user for two numbers. Then print:

  • their sum
  • their difference
  • their product
  • their division

Example:

Give me a number: 10
Give me another number: 2

10 + 2 = 12
10 - 2 = 8
10 * 2 = 20
10 / 2 = 5
x = float(input("Give me a number: "))
y = float(input("Give me another number: "))

print(f"{x} + {y} = {x + y}")
print(f"{x} - {y} = {x - y}")
print(f"{x} * {y} = {x * y}")
print(f"{x} / {y} = {x / y}")
Exercise: Three Password Attempts

Give the user three attempts to enter the password python.

If the password is correct, print Access granted and stop asking.

Otherwise, print Incorrect password.

for attempt in range(1, 4):
    password = input("Password: ")

    if password == "python":
        print("Access granted")
        break
    else:
        print("Incorrect password")

Some More Exercises

Restaurant Bill

Ask the user for:

  • the price of a meal
  • the tip percentage

Then print the tip amount and the final price.

Example:

Meal price: 50
Tip percentage: 10

Tip: 5.0
Total: 55.0
price = float(input("Meal price: "))
percentage = float(input("Tip percentage: "))

tip = price * percentage / 100
total = price + tip

print(f"Tip: {tip}")
print(f"Total: {total}")
Username Length

Ask the user for a username.

If the username has fewer than 5 characters, print:

Username too short

Otherwise, print:

Username accepted
username = input("Username: ")

if len(username) < 5:
    print("Username too short")
else:
    print("Username accepted")
Age in Months

Ask the user for their age in years.

Print their age in months.

Example:

Age: 20
You are approximately 240 months old
age = int(input("Age: "))

months = age * 12

print(f"You are approximately {months} months old")
Number Cleaner

Ask the user for a decimal number.

Then print:

  • the number as a float
  • the number rounded to two decimals
  • the number converted to an integer
  • the absolute value of the number

Example:

Give me a decimal number: -5.678

Float: -5.678
Rounded: -5.68
Integer: -5
Absolute: 5.678
number = float(input("Give me a decimal number: "))

print(f"Float: {number}")
print(f"Rounded: {round(number, 2)}")
print(f"Integer: {int(number)}")
print(f"Absolute: {abs(number)}")

Summary

  • Python has many built-in functions.
  • A function receives input inside parentheses and performs a task.
  • Some functions display information, such as print().Some functions return information, such as type(), len(), round(), and abs().
  • Some functions convert values from one type to another, such as int(), float(), and str().
  • The input() function always returns a string, so we often combine it with int() or float().
  • Functions can also be combined. Python evaluates the inner function first.