CS111: Introduction to the Python Language

The following examples will familiarize you with the Python programming language.
The code is provided in the input cells (notice the labels In [ ]:).
To run the code in a cell, select it (by putting the cursor in the cell) and then click the Run button.
(it looks like the Play in a Music Player interface). Alternatively, press Shift+Return in your keyboard.
You'll see the result in the Out [ ]: cells. You can rerun the code in a cell at any time.
Feel free to change the code to experiment.

1. Simple Expressions: Python as a Calculator

The Python interactive interpreter can perform calculations of different expressions just like a calculator.
Try to guess the result of each input, and then run the code to see the result.
The phrases precedeed by # are comments, they are ignored during the code execution.

In [1]:
3 + 4 * 5 # precedence
Out[1]:
23
In [2]:
(3 + 4) * 5 # override precedence
Out[2]:
35
In [3]:
3 + 4 * 5 # spaces don't matter
Out[3]:
23
In [4]:
17/3 # floating point (decimal) division
Out[4]:
5.666666666666667
In [5]:
17//3 # integer division
Out[5]:
5
In [6]:
17 % 3 # integer remainder (% in this case is known as the modulo operator)
Out[6]:
2
In [7]:
17.0//3 # result of // is a float if either operand is a float. 
Out[7]:
5.0
In [8]:
17//2.5
Out[8]:
6.0
In [9]:
17%2.5
Out[9]:
2.0

Try out an expression of your own in the cell below. For example, an expression that has more than one operator, such as 2 * (3 + 4).

In [10]:
5 + (12 - 7) * 4
Out[10]:
25

Summary

The results of an operator depend on the types of the operand. For example: 7//3 returns 2 and 7.0//3 returns 2.0; neither returns 2.3333, but that is the result of 7/3. Make sure to understand what is the expected value type for a simple expression.

2. Strings and Concatenation

A string is a sequence of characters that we write between a pair of double quotes or a pair of single quotes. Run every cell to see the result.

In [11]:
"CS 111" # the string is within double quotes
Out[11]:
'CS 111'
In [12]:
'rocks!' # we can also use single quotes, it is still a string
Out[12]:
'rocks!'
In [13]:
"CS 111" + 'rocks!' # example of concatenation
Out[13]:
'CS 111rocks!'

The above was an example of string concatenation, chaining two or more strings in one.
How can you fix the issue of the missing space between 111 and rocks?
There are at least three different ways to do that.
Try them out in the cells below and then check them against the given solution.

In [ ]:
 
In [ ]:
 
In [ ]:
 

Solutions:

  1. Add space at the end of first string: "CS 111 " + 'rocks!'
  2. Add space at the start of the second string: "CS 111" + ' rocks!'
  3. Add space as a string on its own: "CS 111" + " " + 'rocks!'

Guess what will happen below:

In [14]:
"111" + 10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/2046617272.py in <module>
----> 1 "111" + 10

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

Don't be scared when you see error messages like this. Instead, read the message carefully to understand what happened. This is a TypeError, which happens when an operator is given operand values with types (e.g. int, float, str) that are not allowed.

How can you fix it?

In [ ]:
# Way #1 to fix is to make "111" a number: 111 + 10 => 121
# Way #2 to fix is to make 10 a string: "111" + "10" => "11110:

Repeated Concatenation: Guess the result!

In [15]:
'123' * 4
Out[15]:
'123123123123'

Summary

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

In [16]:
'cs' * '111'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/562477872.py in <module>
----> 1 'cs' * '111'

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

3. Variables

A variable can be conceptualized as a box containing a value that a programmer names or changes with an assignment statement, using =.
Variables can name any value.
Important: The symbol = is pronounced “gets” not “equals”!

In [17]:
fav = 17 # an assignment statement has no output
In [18]:
fav # this is called "variable reference" and denotes the current value of the variable
Out[18]:
17
In [19]:
fav + fav # this is a simple expression that uses the current value of the variable
Out[19]:
34
In [20]:
lucky = 8
In [21]:
fav + lucky 
Out[21]:
25
In [22]:
aSum = fav + lucky # define a new variable and assign to it the value returned by the expression on the right
In [23]:
aSum * aSum
Out[23]:
625

Let us change the value stored in the variable named fav.

In [24]:
fav = 12

Will this change affect the variable aSum?
How would you check that?

In [25]:
# No, assigning to fav does *not* change the values of previous assignments, other than to fav
# We can check by evaluating aSum:
aSum
Out[25]:
25
In [26]:
fav = fav - lucky # here is yet another change for the value of the variable
# Note that the fav on the right is the current value of fav (which is 12),
# but we're going to change the value of fav to be 12 - 8, which is 4

What is the current value of fav? How would you check that?

In [27]:
fav
Out[27]:
4

An example of doing string concatenation with variables.

In [28]:
name = 'CS111'
name * fav # notice that we can have multiple lines of code in a single cell.
Out[28]:
'CS111CS111CS111CS111'

4. Built-in Functions: max, min, type, len

Finding the maximum or minimum of a series of two or more numbers with max and min.
The inputs to a function are called arguments, they are separated by commas.
Notice that a function has parentheses surrounding the arguments.

In [29]:
min(7, 3)
Out[29]:
3
In [30]:
max(7, 3)
Out[30]:
7
In [31]:
min(7, 3, 2, 9) # notice how we can have as many arguments we want.
Out[31]:
2
In [32]:
smallest = min(-5, 2) # variable smallest gets the output from the function, in this case, -5.
In [33]:
smallest # check the value stored in smallest
Out[33]:
-5
In [34]:
largest = max(-3, -10) # variable largest gets the value -3, which is the output of 
                       # the function call with the arguments -3 and -10
In [35]:
largest #check the value stored in largest
Out[35]:
-3
In [36]:
max(smallest, largest, -1) # we can mix variables and values as function arguments
Out[36]:
-1

Finding the type of a value with the type function.

In [37]:
type(111) # this is an integer value 
Out[37]:
int
In [38]:
type(4.0) # this is a decimal value, also known as a floating point number (because the decimal point can "float")
Out[38]:
float
In [39]:
type("CS111") # this is a string value
Out[39]:
str
In [40]:
type(max(7.3, 4)) # notice how we can nest function calls within each-other
Out[40]:
float
In [41]:
x = "CS111 " + "rocks!"
type(x) # we can also ask for the type of variables, the same way as for values.
Out[41]:
str
In [42]:
# Hey, what's the type of a type like int, float, str?
type(int)
Out[42]:
type
In [43]:
# And what's the type of type? 
type(type)
Out[43]:
type

The function len that returns the number of characters in a string.

In [44]:
len('CS111')
Out[44]:
5
In [45]:
len('CS111 rocks!')  #try to guess before looking it up
Out[45]:
12
In [46]:
len('com' + 'puter') # the expression will be evaluated first, and then the result will be an argument for the function
Out[46]:
8
In [47]:
course = 'computer programming'
len(course)
Out[47]:
20
In [48]:
len(111)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/1919873987.py in <module>
----> 1 len(111)

TypeError: object of type 'int' has no len()

5. More built-in functions: Converting between types with str, int, and float.

The function str

In [49]:
str(17) # convert an integer to string
Out[49]:
'17'
In [50]:
str(4.1) # convert a float to string
Out[50]:
'4.1'
In [51]:
'CS' + 111 # this generates an error, why?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/4238912545.py in <module>
----> 1 'CS' + 111 # this generates an error, why?

TypeError: can only concatenate str (not "int") to str
In [52]:
'CS' + str(111) # this gives the desired output, why?
Out[52]:
'CS111'
In [53]:
len(str(111)) # does len(111) work? 
Out[53]:
3
In [54]:
lenOfName = len('CS' + str(max(110, 111))) # what is the result of this assignment?
In [55]:
str(lenOfName) # what is the output?
Out[55]:
'5'
In [56]:
str("CS11") # what is the output?
Out[56]:
'CS11'
In [57]:
len(str(min(17, 3))) # notice the nesting of many function calls. Which is the order of execution?
Out[57]:
1
In [58]:
str((3 + 4) * len('C' + 'S' + str(max(110, 111)))) # See slide 18 for how this is evaluated
Out[58]:
'35'

The function int

In [59]:
int('42') # convert a string value to integer
Out[59]:
42
In [60]:
int('-273') # it works for negative numbers too
Out[60]:
-273
In [61]:
123 + '42' # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/3479822662.py in <module>
----> 1 123 + '42' # will this work?

TypeError: unsupported operand type(s) for +: 'int' and 'str'

How to fix the above error by using the int function?

In [62]:
123 + int('42')
Out[62]:
165
In [63]:
int('3.141') # will this work? 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/3104556577.py in <module>
----> 1 int('3.141') # will this work?

ValueError: invalid literal for int() with base 10: '3.141'
In [64]:
int('five') # will this work?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/319696527.py in <module>
----> 1 int('five') # will this work?

ValueError: invalid literal for int() with base 10: 'five'
In [65]:
int(98.6) # convert from float to integer
Out[65]:
98
In [66]:
int(-2.978) # what will this output?
Out[66]:
-2
In [67]:
int(422) # what will this output?
Out[67]:
422

The function float

In [68]:
float('3.141') # convert a string value into a float value
Out[68]:
3.141
In [69]:
float('-273.15') # it works for negative values too
Out[69]:
-273.15
In [70]:
float('3') # can you guess the output, why?
Out[70]:
3.0
In [71]:
float('3.1.4') # what is the output for this?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/675095741.py in <module>
----> 1 float('3.1.4') # what is the output for this?

ValueError: could not convert string to float: '3.1.4'
In [72]:
float('pi') # what is the output for this?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/2093184136.py in <module>
----> 1 float('pi') # what is the output for this?

ValueError: could not convert string to float: 'pi'
In [73]:
float(42)   # convert from an integer to float
Out[73]:
42.0

6. Dealing with float values

The unexpected behavior of float values.

In [74]:
2.1 - 2.0 # what is the output value?
Out[74]:
0.10000000000000009
In [75]:
2.2 - 2.0
Out[75]:
0.20000000000000018
In [76]:
2.3 - 2.0
Out[76]:
0.2999999999999998
In [77]:
1.3 - 1.0
Out[77]:
0.30000000000000004
In [78]:
100.3 - 100.0
Out[78]:
0.29999999999999716
In [79]:
10/3
Out[79]:
3.3333333333333335
In [80]:
1.414*(3.14159/1.414)
Out[80]:
3.1415900000000003

Fixing the behavior with round

In [81]:
round(3.14156)  # round the value to the closest integer
Out[81]:
3
In [82]:
round(98.6) # round to the closest integer
Out[82]:
99

The function round can be used with one or two arguments. We just saw that use with one argument.
Now let's check out the output when there are two arguments.
Try to guess what the second argument is doing.

In [83]:
round(3.14156, 2)
Out[83]:
3.14
In [84]:
round(3.14156, 1)
Out[84]:
3.1
In [85]:
round(3.14156, 0)
Out[85]:
3.0
In [86]:
# round will round up if next digit is 5 or more
round(3.14156, 4)
Out[86]:
3.1416
In [87]:
round(2.3 - 2.0, 1) # what will the result be this time?
Out[87]:
0.3

7. The useful print function

This function will display characters on the screen.
Notice how we will not see the output fields labeled with Out[] when we use print.

In [88]:
print(7)
7
In [89]:
print('CS111')
CS111
In [90]:
print('CS' + str(111)) # it prints the result of the expression
CS111
In [91]:
print(len(str('CS111')) * min(17,3)) # notice the nested functions. What will the displayed?
15
In [92]:
college = 'Wellesley'
print('I go to ' + college) # expressions can combine values and variables
I go to Wellesley
In [93]:
dollars = 10
print('The movie costs $' + str(dollars) + '.') # concatenation of string values
The movie costs $10.

When print is called with multiple arguments, it prints them all, separated by spaces.

In [94]:
print(1 + 2, 6 * 7, 'CS' + '111') 
3 42 CS111
In [95]:
print(1,'+',2,'=',1+2)
1 + 2 = 3

The default space printed between multiple arguments to print can be changed by the keyword argument sep=string

In [96]:
print(1,'+',2,'=',1+2, sep='||') # separate printed values by two vertical bars
1||+||2||=||3
In [97]:
print(1,'+',2,'=',1+2, sep=', ') # separate printed values by a comma and space
1, +, 2, =, 3
In [98]:
print(1,'+',2,'=',1+2, sep='') # separate printed values by no characters (the empty string)
1+2=3

When \n appears in a string, it represents a single character call the newline character. When printed, it causes the display to go to the next line.

In [99]:
print('a\nbc\ndef')
a
bc
def
In [100]:
len('a\nbc\ndef') # \n counts as a single character
Out[100]:
8

Expression values vs. print

In the lines below, notice what happens when you execute the cell. Notice that sometimes you see an output cell, and sometimes you don't.

In [101]:
max(10, 20)
Out[101]:
20
In [102]:
print(max(10, 20))
20
In [103]:
10 + 20
Out[103]:
30
In [104]:
print (10 + 20)
30
In [105]:
message = "Welcome to CS 111" 

Question: why don't we see anything after executing the above cell?

In [106]:
message
Out[106]:
'Welcome to CS 111'
In [107]:
print(message)
Welcome to CS 111

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, so calling print acts like a statement rather than an expression.

To emphasize that calls to print act like statements rather than expressions, Thonny hides the None value returned by print and only outputs the printed expression. But there are situations in which the hidden None value can be exposed, like the following:

In [108]:
str(print(print('CS'), print(111))) # Explain why each result line is the way it is!
CS
111
None None
Out[108]:
'None'

8. Building interactive programs with input

An alternative to "hard-coding" values in a program is to create an interactive program that asks the user for input. The built-in function input does exactly that.

In [109]:
input('Enter your name: ') # waits for user to provide an input value and then outputs the entry
Enter your name: Olivia
Out[109]:
'Olivia'
In [110]:
age = input('Enter your age: ')  # we can store the entered input into a variable
Enter your age: 18
In [111]:
age # what value is stored and of what type?
Out[111]:
'18'
In [112]:
age + 4 # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/3158414335.py in <module>
----> 1 age + 4 # will this work?

TypeError: can only concatenate str (not "int") to str
In [113]:
age = float(input('Enter your age: ')) # perform conversion before storing the value
Enter your age: 18
In [114]:
age + 4 # will this work now?
Out[114]:
22.0

9. Error Types and Messages

Try to guess what error type and message will appear in the examples below:

In [115]:
"CS" + 111
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/1595607989.py in <module>
----> 1 "CS" + 111

TypeError: can only concatenate str (not "int") to str
In [116]:
2017 + "'s record"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/2659262599.py in <module>
----> 1 2017 + "'s record"

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [117]:
year = 2017
len(year)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/1233489908.py in <module>
      1 year = 2017
----> 2 len(year)

TypeError: object of type 'int' has no len()
In [118]:
month + 1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/3258978334.py in <module>
----> 1 month + 1

NameError: name 'month' is not defined
In [119]:
float("e")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/1927773460.py in <module>
----> 1 float("e")

ValueError: could not convert string to float: 'e'
In [120]:
int('2.7182')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/2814902638.py in <module>
----> 1 int('2.7182')

ValueError: invalid literal for int() with base 10: '2.7182'
In [121]:
first-name = "Harry" # variable names can't include hyphens, which look to Python like a minus operator
                     # use underscores instead, as in first_name
  File "/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/911258945.py", line 1
    first-name = "Harry" # variable names can't include hyphens, which look to Python like a minus operator
                                                                                                           ^
SyntaxError: can't assign to operator
In [122]:
1 + age = 17 # Can't assign to the result of an addition operator.
  File "/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/1982377060.py", line 1
    1 + age = 17 # Can't assign to the result of an addition operator.
                                                                      ^
SyntaxError: can't assign to operator
In [123]:
1 + (age = 17) # Can't add a number and an assignment statement, 
               # because an assignment statement doesn't denote a values
  File "/var/folders/xz/kvwfdnnx1tdbcd8fc_h7h__c0000gn/T/ipykernel_4246/1074331834.py", line 1
    1 + (age = 17) # Can't add a number and an assignment statement,
             ^
SyntaxError: invalid syntax

10. Test your knowledge

Use this section to try to answer the questions in the final slide of Lecture 2.

To create new cells, press the + button in the menu bar.

In [ ]:
 

11. Drills for Python Basics

Compute 5 plus 6 and put it in the variable x

In [124]:
# You write:
x = 5 + 6

assert x == 11
print('Success!')
Success!

Compute 7 plus 15 and put it in the variable y

In [127]:
# Your code here:
y = 7 + 15
In [128]:
assert y == 22
print('Success!')
Success!

Compute 15 times 5 and put it in the variable z

In [129]:
# Your code here:
z = 15 * 5
In [130]:
assert z == 75
print('Success!')
Success!

Compute the remainder of dividing 15 by 5 and put it in the variable a

In [132]:
# Your code here:
a = 15 % 5
In [133]:
assert a == 0
print('Success!')
Success!

Compute the remainder of dividing 34 by 3 and put it in the variable h

In [134]:
# Your code here:
h = 34 % 3
In [135]:
assert h == 1
print('Success!')
Success!

Compute 6 divided by 12 and put it in the variable b

In [136]:
# Your code here:
b = 6 / 12
In [137]:
assert b == 0.5
print('Success!')
Success!

Concatenate the strings 'arbitrary' and 'string' and put it in the variable c

In [138]:
# Your code here:
c = 'arbitrary' + 'string'
In [139]:
assert c == 'arbitrarystring'
print('Success!')
Success!

Create the string consisting of 1000 copies of the letter 'q' and put it in the variable d. Don't type 'q' 1000 times!

In [140]:
# Your code here:
d = 1000 * 'q'
In [141]:
assert len(d) == 1000 and set(d) == {'q'}
print('Success!')
Success!

Use length and width to compute the area of a rectangle and store it in the area variable.

In [142]:
length = 5
width = 7.5

# Your code here:
area = length * width
In [143]:
assert area == 37.5
print('Success!')
Success!

Use radius and math.pi to compute the area of a circle and store it in the area variable.

In [144]:
import math
radius = 7.3

# Your code here:
area = radius * radius * math.pi
In [145]:
assert area == 167.41547250980008
print('Success!')
Success!

Convert the given string into an integer and store the number in the variable intified

In [148]:
s = '15'

# Your code here:
intified = int(s)
In [149]:
assert intified == 15
assert type(intified) == int
print('Success!')
Success!

Convert the given string into an floating point number and store it the variable floating

In [150]:
s = '19.2'

# Your code here:
floating = float(s)
In [151]:
assert floating == 19.2
assert type(floating) == float
print('Success!')
Success!

Make the string 'I am 1000 years old' using an expression with s1, s2, and age, and store the result in the string claim

In [152]:
s1 = 'I am '
s2 = ' years old'
age = 1000

# Your code here:
claim = s1 + str(age) + s2
In [153]:
assert claim == 'I am 1000 years old'
assert type(claim) == str
print('Success!')
Success!

Make the string 'I have 956 pizzas' using an expression with s1, s2, p1, and p2, and store the result in the string claim

In [154]:
s1 = 'I have '
s2 = ' pizzas'
p1 = 400
p2 = 556

# Your code here:
claim = s1 + str(p1 + p2) + s2
In [155]:
assert claim == 'I have 956 pizzas'
assert type(claim) == str
print('Success!')
Success!