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 [20]:
3 + 4 * 5 # precedence
Out[20]:
23
In [21]:
(3 + 4) * 5 # override precedence
Out[21]:
35
In [22]:
3 + 4 * 5 # spaces don't matter
Out[22]:
23
In [23]:
17/3 # floating point (decimal) division
Out[23]:
5.666666666666667
In [24]:
17//3 # integer division
Out[24]:
5
In [25]:
17 % 3 # integer remainder (% in this case is known as the modulo operator)
Out[25]:
2
In [26]:
17.0//3 # result of // is a float if either operand is a float. 
Out[26]:
5.0
In [27]:
17//2.5
Out[27]:
6.0
In [28]:
17%2.5
Out[28]:
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 [29]:
5 + (12 - 7) * 4
Out[29]:
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 [30]:
"CS 111" # the string is within double quotes
Out[30]:
'CS 111'
In [31]:
'rocks!' # we can also use single quotes, it is still a string
Out[31]:
'rocks!'
In [32]:
"CS 111" + 'rocks!' # example of concatenation
Out[32]:
'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 [33]:
"111" + 10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89529/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 [ ]:
'123' * 4

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 [ ]:
'cs' * '111'

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 [ ]:
fav = 17 # an assignment statement has no output
In [ ]:
fav # this is called "variable reference" and denotes the current value of the variable
In [ ]:
fav + fav # this is a simple expression that uses the current value of the variable
In [ ]:
lucky = 8
In [ ]:
fav + lucky 
In [ ]:
aSum = fav + lucky # define a new variable and assign to it the value returned by the expression on the right
In [ ]:
aSum * aSum

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

In [ ]:
fav = 12

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

In [ ]:
# No, assigning to fav does *not* change the values of previous assignments, other than to fav
# We can check by evaluating aSum:
aSum
In [ ]:
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 [ ]:
fav

An example of doing string concatenation with variables.

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

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 [ ]:
min(7, 3)
In [ ]:
max(7, 3)
In [ ]:
min(7, 3, 2, 9) # notice how we can have as many arguments we want.
In [ ]:
smallest = min(-5, 2) # variable smallest gets the output from the function, in this case, -5.
In [ ]:
smallest # check the value stored in smallest
In [ ]:
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 [34]:
largest #check the value stored in largest
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89529/3940115642.py in <module>
----> 1 largest #check the value stored in largest

NameError: name 'largest' is not defined
In [ ]:
max(smallest, largest, -1) # we can mix variables and values as function arguments

Finding the type of a value with the type function.

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

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

In [ ]:
len('CS111')
In [ ]:
len('CS111 rocks!')  #try to guess before looking it up
In [ ]:
len('com' + 'puter') # the expression will be evaluated first, and then the result will be an argument for the function
In [ ]:
course = 'computer programming'
len(course)
In [ ]:
len(111)

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

The function str

In [35]:
str(17) # convert an integer to string
Out[35]:
'17'
In [36]:
str(4.1) # convert a float to string
Out[36]:
'4.1'
In [37]:
'CS' + 111 # this generates an error, why?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89529/4238912545.py in <module>
----> 1 'CS' + 111 # this generates an error, why?

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

The function int

In [38]:
int('42') # convert a string value to integer
Out[38]:
42
In [39]:
int('-273') # it works for negative numbers too
Out[39]:
-273
In [40]:
123 + '42' # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89529/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 [1]:
123 + int('42')
Out[1]:
165
In [2]:
int('3.141') # will this work? 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89551/3104556577.py in <module>
----> 1 int('3.141') # will this work?

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

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

The function float

In [7]:
float('3.141') # convert a string value into a float value
Out[7]:
3.141
In [8]:
float('-273.15') # it works for negative values too
Out[8]:
-273.15
In [9]:
float('3') # can you guess the output, why?
Out[9]:
3.0
In [10]:
float('3.1.4') # what is the output for this?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89551/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 [ ]:
float('pi') # what is the output for this?
In [ ]:
float(42)   # convert from an integer to float

6. Dealing with float values

The unexpected behavior of float values.

In [ ]:
2.1 - 2.0 # what is the output value?
In [ ]:
2.2 - 2.0
In [11]:
2.3 - 2.0
Out[11]:
0.2999999999999998
In [12]:
1.3 - 1.0
Out[12]:
0.30000000000000004
In [13]:
100.3 - 100.0
Out[13]:
0.29999999999999716
In [14]:
10/3
Out[14]:
3.3333333333333335
In [15]:
1.414*(3.14159/1.414)
Out[15]:
3.1415900000000003

Fixing the behavior with round

In [16]:
round(3.14156)  # round the value to the closest integer
Out[16]:
3
In [17]:
round(98.6) # round to the closest integer
Out[17]:
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 [18]:
round(3.14156, 2)
Out[18]:
3.14
In [19]:
round(3.14156, 1)
Out[19]:
3.1
In [20]:
round(3.14156, 0)
Out[20]:
3.0
In [21]:
# round will round up if next digit is 5 or more
round(3.14156, 4)
Out[21]:
3.1416
In [22]:
round(2.3 - 2.0, 1) # what will the result be this time?
Out[22]:
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 [23]:
print(7)
7
In [24]:
print('CS111')
CS111
In [25]:
print('CS' + str(111)) # it prints the result of the expression
CS111
In [26]:
print(len(str('CS111')) * min(17,3)) # notice the nested functions. What will the displayed?
15
In [27]:
college = 'Wellesley'
print('I go to ' + college) # expressions can combine values and variables
I go to Wellesley
In [28]:
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 [29]:
print(1 + 2, 6 * 7, 'CS' + '111') 
3 42 CS111
In [30]:
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 [31]:
print(1,'+',2,'=',1+2, sep='||') # separate printed values by two vertical bars
1||+||2||=||3
In [32]:
print(1,'+',2,'=',1+2, sep=', ') # separate printed values by a comma and space
1, +, 2, =, 3
In [33]:
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 [34]:
print('a\nbc\ndef')
a
bc
def
In [35]:
len('a\nbc\ndef') # \n counts as a single character
Out[35]:
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 [36]:
max(10, 20)
Out[36]:
20
In [37]:
print(max(10, 20))
20
In [38]:
10 + 20
Out[38]:
30
In [39]:
print (10 + 20)
30
In [40]:
message = "Welcome to CS 111" 

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

In [41]:
message
Out[41]:
'Welcome to CS 111'
In [42]:
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 [43]:
str(print(print('CS'), print(111))) # Explain why each result line is the way it is!
CS
111
None None
Out[43]:
'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 [44]:
input('Enter your name: ') # waits for user to provide an input value and then outputs the entry
Enter your name: Peter
Out[44]:
'Peter'
In [45]:
age = input('Enter your age: ')  # we can store the entered input into a variable
Enter your age: 36
In [46]:
age # what value is stored and of what type?
Out[46]:
'36'
In [47]:
age + 4 # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89551/3158414335.py in <module>
----> 1 age + 4 # will this work?

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

9. Error Types and Messages

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

In [50]:
"CS" + 111
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89551/1595607989.py in <module>
----> 1 "CS" + 111

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

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

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

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

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

ValueError: invalid literal for int() with base 10: '2.7182'
In [69]:
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/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89551/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 [70]:
1 + age = 17 # Can't assign to the result of an addition operator.
  File "/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89551/1982377060.py", line 1
    1 + age = 17 # Can't assign to the result of an addition operator.
                                                                      ^
SyntaxError: can't assign to operator
In [71]:
1 + (age = 17) # Can't add a number and an assignment statement, 
               # because an assignment statement doesn't denote a values
  File "/var/folders/sb/njhjnvlx3wz0f_8l_szm1m000000gp/T/ipykernel_89551/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 [ ]:
 
In [ ]: