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)
Cell In[14], line 1
----> 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 [15]:
# 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 [16]:
'123' * 4
Out[16]:
'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 [17]:
'cs' * '111'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[17], line 1
----> 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 [18]:
fav = 17 # an assignment statement has no output
In [19]:
fav # this is called "variable reference" and denotes the current value of the variable
Out[19]:
17
In [20]:
fav + fav # this is a simple expression that uses the current value of the variable
Out[20]:
34
In [21]:
lucky = 8
In [22]:
fav + lucky
Out[22]:
25
In [23]:
aSum = fav + lucky # define a new variable and assign to it the value returned by the expression on the right
In [24]:
aSum * aSum
Out[24]:
625

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

In [25]:
fav = 11

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

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

An example of doing string concatenation with variables.

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

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 [30]:
min(7, 3)
Out[30]:
3
In [31]:
max(7, 3)
Out[31]:
7
In [32]:
min(7, 3, 2, 9) # notice how we can have as many arguments we want.
Out[32]:
2
In [33]:
smallest = min(-5, 2) # variable smallest gets the output from the function, in this case, -5.
In [34]:
smallest # check the value stored in smallest
Out[34]:
-5
In [35]:
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 [36]:
largest #check the value stored in largest
Out[36]:
-3
In [37]:
max(smallest, largest, -1) # we can mix variables and values as function arguments
Out[37]:
-1

Finding the type of a value with the type function.

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

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

In [45]:
len('CS111')
Out[45]:
5
In [46]:
len('CS111 rocks!')  #try to guess before looking it up
Out[46]:
12
In [47]:
len('com' + 'puter') # the expression will be evaluated first, and then the result will be an argument for the function
Out[47]:
8
In [48]:
course = 'computer programming'
len(course)
Out[48]:
20
In [49]:
len(111)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[49], line 1
----> 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 [50]:
str(17) # convert an integer to string
Out[50]:
'17'
In [51]:
str(4.1) # convert a float to string
Out[51]:
'4.1'
In [52]:
'CS' + 111 # this generates an error, why?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[52], line 1
----> 1 'CS' + 111 # this generates an error, why?

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

The function int

In [60]:
int('42') # convert a string value to integer
Out[60]:
42
In [61]:
int('-273') # it works for negative numbers too
Out[61]:
-273
In [62]:
123 + '42' # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[62], line 1
----> 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 [63]:
123 + int('42')
Out[63]:
165
In [64]:
int('3.141') # will this work?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[64], line 1
----> 1 int('3.141') # will this work? 

ValueError: invalid literal for int() with base 10: '3.141'
In [65]:
int('five') # will this work?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[65], line 1
----> 1 int('five') # will this work?

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

The function float

In [69]:
float('3.141') # convert a string value into a float value
Out[69]:
3.141
In [70]:
float('-273.15') # it works for negative values too
Out[70]:
-273.15
In [71]:
float('3') # can you guess the output, why?
Out[71]:
3.0
In [72]:
float('3.1.4') # what is the output for this?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[72], line 1
----> 1 float('3.1.4') # what is the output for this?

ValueError: could not convert string to float: '3.1.4'
In [73]:
float('pi') # what is the output for this?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[73], line 1
----> 1 float('pi') # what is the output for this?

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

6. Dealing with float values

The unexpected behavior of float values.

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

Fixing the behavior with round

In [82]:
round(3.14156)  # round the value to the closest integer
Out[82]:
3
In [83]:
round(98.6) # round to the closest integer
Out[83]:
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 [84]:
round(3.14156, 2)
Out[84]:
3.14
In [85]:
round(3.14156, 1)
Out[85]:
3.1
In [86]:
round(3.14156, 0)
Out[86]:
3.0
In [87]:
# round will round up if next digit is 5 or more
round(3.14156, 4)
Out[87]:
3.1416
In [88]:
round(2.3 - 2.0, 1) # what will the result be this time?
Out[88]:
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 [89]:
print(7)
7
In [90]:
print('CS111')
CS111
In [91]:
print('CS' + str(111)) # it prints the result of the expression
CS111
In [92]:
print(len(str('CS111')) * min(17,3)) # notice the nested functions. What will the displayed?
15
In [93]:
college = 'Wellesley'
print('I go to ' + college) # expressions can combine values and variables
I go to Wellesley
In [94]:
dollars = 10
print('The movie costs $' + str(dollars) + '.') # concatenation of string values
The movie costs $10.

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 [95]:
print('a\nbc\ndef')
a
bc
def
In [96]:
len('a\nbc\ndef') # \n counts as a single character
Out[96]:
8

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

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

Calling print with multiple argument values is helpful because it avoids (1) having to converts some of those values to strings and (2) having to use + to concatenate strings. Compare how much more complex the last example above would be without multiple arguments:

In [99]:
print(str(6) + ' * ' + str(7) + ' = ' + str(6*7))
6 * 7 = 42

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

In [100]:
print(6,'*',7,'=',6*7, sep='$') # separate printed values by dollar signs
6$*$7$=$42
In [101]:
print(6,'*',7,'=',6*7, sep=', ') # separate printed values by a comma and space
6, *, 7, =, 42
In [102]:
print(6,'*',7,'=',6*7, sep='') # separate printed values by zero characters (the empty string)
6*7=42
In [103]:
print(6,'*',7,'=',6*7, sep='\n') # separate printed values newlines
6
*
7
=
42

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 [104]:
max(10, 20)
Out[104]:
20
In [105]:
print(max(10, 20))
20
In [106]:
10 + 20
Out[106]:
30
In [107]:
print (10 + 20)
30
In [108]:
message = "Welcome to CS 111"

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

In [109]:
message
Out[109]:
'Welcome to CS 111'
In [110]:
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 (which has type NoneType). 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 [111]:
str(print('Hi!'))
Hi!
Out[111]:
'None'
In [112]:
print(print(6*7))
42
None
In [113]:
type(print(print('CS'), print(111))) # Explain why each result line is the way it is!
CS
111
None None
Out[113]:
NoneType

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 [114]:
input('Enter your name: ') # waits for user to provide an input value and then outputs the entry
Enter your name: Lyn
Out[114]:
'Lyn'
In [115]:
age = input('Enter your age: ')  # we can store the entered input into a variable
Enter your age: 62
In [116]:
age # what value is stored and of what type?
Out[116]:
'62'
In [117]:
age + 4 # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[117], line 1
----> 1 age + 4 # will this work?

TypeError: can only concatenate str (not "int") to str
In [118]:
age = float(input('Enter your age: ')) # perform conversion before storing the value
Enter your age: 62
In [119]:
age + 2 # will this work now?
Out[119]:
64.0

9. Error Types and Messages

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

In [120]:
"CS" + 111
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[120], line 1
----> 1 "CS" + 111

TypeError: can only concatenate str (not "int") to str
In [121]:
2017 + "'s record"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[121], line 1
----> 1 2017 + "'s record"

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [122]:
year = 2017
len(year)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[122], line 2
      1 year = 2017
----> 2 len(year)

TypeError: object of type 'int' has no len()
In [123]:
month + 1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[123], line 1
----> 1 month + 1

NameError: name 'month' is not defined
In [124]:
float("e")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[124], line 1
----> 1 float("e")

ValueError: could not convert string to float: 'e'
In [125]:
int('2.7182')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[125], line 1
----> 1 int('2.7182')

ValueError: invalid literal for int() with base 10: '2.7182'
In [126]:
first-name = "Harry" # variable names can't include hyphens, which look to Python like a minus operator
                     # use underscores instead, as in first_name
  Cell In[126], line 1
    first-name = "Harry" # variable names can't include hyphens, which look to Python like a minus operator
    ^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
In [127]:
1 + age = 17 # Can't assign to the result of an addition operator.
  Cell In[127], line 1
    1 + age = 17 # Can't assign to the result of an addition operator.
    ^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
In [128]:
1 + (age = 17) # Can't add a number and an assignment statement, 
               # because an assignment statement doesn't denote a values
  Cell In[128], line 1
    1 + (age = 17) # Can't add a number and an assignment statement,
         ^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

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 [ ]: