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.

type(134)
int
type('134')  # single quotes
str
type("134")  # double quotes
str
type(3.14159)
float
type('')
str
type(0)
int
type(False)
bool
type(True)
bool
type(None)
NoneType
type(1000 / 3) # What will this return?
float
type(1000 % 3) # How about this?
int

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
18
11 - 7
4
19 / 3  # floating point division
6.333333333333333
19 // 3 # integer division
6
19 // 3.0 # what type will this return?
6.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.

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

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.

"Happy" # the string is within double quotes
'Happy'
'Birthday!' # we can also use single quotes, it is still a string
'Birthday!'
"Happy" + 'Birthday' # example of string concatenation
'HappyBirthday'
"Happy " + 'Birthday' #space is a character and matters in strings
'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)
/var/folders/md/kwd9nc_d2ns0hw9wsvdrnt2c0000gn/T/ipykernel_39331/3981948486.py in <module>
----> 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
'*Williams**Williams**Williams*'
'*Williams*' * 2.0 # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/md/kwd9nc_d2ns0hw9wsvdrnt2c0000gn/T/ipykernel_39331/277076085.py in <module>
----> 1 '*Williams*' * 2.0 # will this work?

TypeError: can't multiply sequence by non-int of type 'float'
'x' * 'y'  # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/md/kwd9nc_d2ns0hw9wsvdrnt2c0000gn/T/ipykernel_39331/874766999.py in <module>
----> 1 'x' * 'y'  # will this work?

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 referred to as “gets” or “is assigned to“, but not “equals”!

num = 23 # what does this do

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.

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

Question. Why does changing sec not change totalsec?

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

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.

print()

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.

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
2
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

input()

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.

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

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

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

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

int()

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

age = input('Enter your age: ')
age
int(age)
int('45.78') # will this work?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/md/kwd9nc_d2ns0hw9wsvdrnt2c0000gn/T/ipykernel_39331/2586540895.py in <module>
----> 1 int('45.78') # will this work?

ValueError: invalid literal for int() with base 10: '45.78'
pi = 3.14159
int(pi)  # what does this return?
3
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.

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

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 2021)

  • print the result

# Lets write this together

age = int(input("Enter your age: "))
print("Year you were born is: ", 2011-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.

str(134)
'134'
'CS' + str(134)
'CS134'
str(15.89797)
'15.89797'
str(***)  # Will this work?
  File "/var/folders/md/kwd9nc_d2ns0hw9wsvdrnt2c0000gn/T/ipykernel_39331/1973408177.py", line 1
    str(***)  # Will this work?
          ^
SyntaxError: invalid syntax
str(0)
'0'
str(True) # What about this?
'True'
str(None) # And this?
'None'
college = 'Williams'
print('I go to ' + college) # expressions can combine values and variables
I go to Williams
dollars = 10
print('The burrito costs $' + str(dollars) + '.') 
The burrito costs $10.

float()

  • 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

float('3.141') # convert a string value into a float value
3.141
float('-273.15') # it works for negative values too
-273.15
float('3') # what does this return?
3.0
float('3.1.4') # will this work?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/md/kwd9nc_d2ns0hw9wsvdrnt2c0000gn/T/ipykernel_39331/1032522168.py in <module>
----> 1 float('3.1.4') # will this work?

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

[Extra] Other Fun Experiments

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

Expressions vs print()

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

100//2
50
print(100//2)
50
message = "Welcome Eephs" # will there be an ouput?
message  # what about now?
'Welcome Eephs'
print(message) # difference between reference and printing
Welcome Eephs

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:

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