Types and Expressions

Jupyter Notebooks provide a rich interface to interactive Python. To read more about how to use them, check out our How To Jupyter guide.

Types in Python

The built-in type() function lets us see the data type of various values in Python.

Note: The one line phrases after # are comments, they are ignored during execution.

# single quotes
# double quotes
# What will this return?
type(1000 / 3) 
# How about this?
type(1000 % 3) 

Simple Expressions using Ints and Floats

The Python interactive interpreter can perform calculations of different expressions just like a calculator.

Let’s try some simple arithmetic expressions below.

11 + 7
11 - 7
# floating point division
19 / 3  
# integer division
19 // 3 
# what type will this return?
19 // 3.0 

Takeway: The results of an expression depends on both the operator used and the types of the operands. For example: 19//3 returns 6 and 19//3.0 returns 6.0; neither returns 6.3333, which is the result of 19/3.

# modulo operator - computes remainder 
23 % 5 
# exponentiation
2 ** 3  
3 + 4 * 5
# parentheses can be used to override 
# operator precedence (or order of operations)
(3 + 4) * 5 

Simple Expressions Using Strings

A string is a sequence of characters that we write between a pair of double quotes or a pair of single quotes.

# the string is within double quotes
# we can also use single quotes, it is still a string
# example of string concatenation
"Happy" + 'Birthday' 
# space is a character and matters in strings
"Happy " + 'Birthday' 
'Happy Birthday'

String concatenation is the operation of chaining two or more strings together to form one string.

Notice that the operator ‘+’ behaves differently depending on the the type of its operands.

  • When + is applied to ints or floats, it adds them mathematically.

  • When + is applied to strings, it concatenates them.

What if we apply + to a combination of int and str? Guess what will happen below:

"CS" + 134
TypeError                                 Traceback (most recent call last)
Input In [25], in <cell line: 1>()
----> 1 "CS" + 134

TypeError: can only concatenate str (not "int") to str

This results in a TypeError, which happens when an operator is given operand values with types (e.g. int, float, str) that do not correspond to the expected type. You cannot add a string to an integer. That does not make sense.

How can we fix the expression, so that it no longer leads to an error?

"CS " + "134"
'CS 134'

Multiplication operator on strings: What do you think will happens if we do this:

'*Williams*' * 3
# will this work?
'*Williams*' * 2.0 
TypeError                                 Traceback (most recent call last)
Input In [28], in <cell line: 2>()
      1 # will this work?
----> 2 '*Williams*' * 2.0

TypeError: can't multiply sequence by non-int of type 'float'
# will this work?
'x' * 'y'  
TypeError                                 Traceback (most recent call last)
Input In [29], in <cell line: 2>()
      1 # will this work?
----> 2 'x' * 'y'

TypeError: can't multiply sequence by non-int of type 'str'

Summary: The operators + and * are the only ones you can use with values of type string. Both of these operators generate concatenated strings. Be careful when using the * operator. One of the operands needs to be an integer value.

Variables and Assignment

Variables are used to give names to values using the assignment operator (=). A variable is essentially a placeholder for a stored value that you want to reuse or update later in the program.

Important: To avoid confusion, the symbol = is sometimes referred to as “gets” or “is assigned to“, but not “equals”!

# what does this do
num = 23 

Notice: The above statement did not produce an output (that is, no Out[] cell). The statement defines the variable num and assigns it the value 23.

# once a variable is defined, we can "refer" to it 
# and ask for its current value
# to evaluate this expression, python first replaces num with its value and then performs the operation
num * 2 
# updating value of num (right evaluated first, and new 
# value assigned to variable on left)
# same as num = num + 1
num *= 2  
# what will be printed?
# can define two variables in one line using a semi colon
mins = 2; sec = 30 
totalsec = (mins * 60) + sec
# update secs variable
sec = 10 
# what is in variable totalsecs now?

Question. Why does changing sec not change totalsec?

totalsec = (mins * 60) + sec
# how about now?

Built-in Functions: print(), input(), int()

Python comes with a ton of built-in capabilities. In this section we will explore some useful built-in functions.


The print() function is used to display characters on the screen. When we print something, notice that there is no output (no Out[] cell). This is because it does not return a value as an output (like a Python expression). It simply performs an action. (We’ll revisit what it means to “return” a value soon.)

print('Welcome to Computer Science')
Welcome to Computer Science

Also notice there are no quotation arounds the printed text. Technically it is not a string!

print(50 % 4)  # we can put Python expressions within a print statement directly
print('****' + '####' + '$$$$')

When print() is called with multiple arguments, it prints them all, separated by spaces. (Arguments are the values inside of the parentheses, separated by commas.)

print('hakuna', 'matata', 24*7) 
hakuna matata 168
num1 = 3; num2 = 5
print(num1, '+', num2, '=', num1+num2)
3 + 5 = 8


The input() function is used to take input from the user. We specify the prompt we want the user to see within the parentheses. By default, input values are always of type string.

# the string within the parens is the prompt the 
# user will see in the terminal
input('Enter your name') 

Notice: Unlike the print() function, input() returns a value (which is just the input entered by user).

# input with a colon and space, sometimes easier 
# for user to understand in terminal
input('Enter your age: ') 

Notice: Notice anything about the type of the input value?


The int() function is used to convert strings of digits to integers.

age = input('Enter your age: ')
NameError                                 Traceback (most recent call last)
Input In [51], in <cell line: 1>()
----> 1 type(age)

NameError: name 'age' is not defined
# will this work?
ValueError                                Traceback (most recent call last)
Input In [53], in <cell line: 2>()
      1 # will this work?
----> 2 int('45.78')

ValueError: invalid literal for int() with base 10: '45.78'
pi = 3.14159
# what does this return?
input('Enter the radius: ')
  • Suppose I want to compute the area of a circle, given the radius inputted by the user. How do I do that?

  • What did I need to do differently?

Let us redo the input statement so that we can compute the area.

# take input from user again
r = int(input("Enter integer radius: ")) 
# compute area
area = pi * (r**2) 

Summary of int()

  • When given a string that is a sequence of digits (optionally preceded by +/-), the int() function returns the corresponding integer; on any other string it results in a ValueError

  • When given a float value, the int() function returns the integer formed by truncating it towards zero

  • When given an integer, the int() function returns that same integer

[Extra] Putting it all together

Now that we know how to take user input, store it, use it to compute simple expressions, and print values, we are ready to put it all to good use.

Let us write a short Python program that:

  • take as input the current age of the user

  • computes the year they were born (assuming current year is 2022)

  • print the result

age = int(input("Enter your age: "))
print("Year you were born is: ", 2022-age)

[Extra] str() and float()

Similar to int(), Python also provides the built-in functions str() and float():

str(): Given a value of another type, the str() function converts it to a string type and returns it.

'CS' + str(134)
# Will this work?
  Input In [62]
SyntaxError: invalid syntax
# What about this?
# And this?
# expressions can combine values and variables
college = 'Williams'
print('I go to ' + college) 
I go to Williams
dollars = 10
print('The burrito costs $' + str(dollars) + '.') 
The burrito costs $10.


  • When given a string that’s a sequence of digits that is a valid representation of a floating point number (optionally preceded by +/-, or including one decimal point), float() turns it into type float and returns it; on any other string it raises a ValueError.

  • When given an integer, float() converts it to a floating point number and returns it

  • When given a floating point number, float() returns that number

# convert a string value into a float value
# it works for negative values too
# what does this return?
# will this work?
ValueError                                Traceback (most recent call last)
Input In [71], in <cell line: 2>()
      1 # will this work?
----> 2 float('3.1.4')

ValueError: could not convert string to float: '3.1.4'

[Extra] Other Fun Experiments

# what is the type of int?
# what is type of type?

Expressions vs print()

Expressions returns value, while print only displays text. Notice the differences below.

# will there be an ouput?
message = "Welcome Ephs" 
# what about now?
'Welcome Ephs'
# difference between reference and printing
Welcome Ephs

Question: Can you notice the difference between the two lines above? Why do you think they are different?

It turns out that calling print() returns the special None value. Python uses a None return value to indicate the function was called for its effect (the action it performs) rather than its value. Calling print() acts like a statement rather than an expression.

To emphasize that calls to print() act like statements rather than expressions, Jupyter hides the None value returned by print(), and shows no Out[] line. But there are situations in which the hidden None value can be exposed, like the following:

# how can we explain this?
str(print(print('CS'), print(134))) 
None None