CS111 Lecture 2: Introduction to the Python Language

Viewing Advice: If you don't see a menu bar at the top of this document, navigate to
Canopy | Preferences | Python | PyLab backend and set it to Inline(SVG).

This notebook accompanies the lecture notes of Lecture 2: 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.

Simple Expressions: Python as a Calculator [Slide 2-5]

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]:
13/3 # integer division
Out[3]:
4
In [4]:
13/3.0 # floating point (decimal) division
Out[4]:
4.333333333333333
In [5]:
13.0 / 3 # decimal division (notice the space between values and operators doesn't matter)
Out[5]:
4.333333333333333
In [6]:
13 % 3 # integer remainder (% in this case is known as the modulo operator)
Out[6]:
1

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 [7]:
4 + 1 * 5
Out[7]:
9

Summary: Values of different types behave differently from what you might expect. For example: 1/3 will generate 0, not 0.3333. Make sure to understand what is the expected value type for a simple expression.

Strings and Concatenation [Slide 2-6]

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 [8]:
"CS 111" # the string is within double quotes
Out[8]:
'CS 111'
In [9]:
'rocks!' # we can also use single quotes, it is still a string
Out[9]:
'rocks!'
In [10]:
"CS 111" + 'rocks!' # example of concatenation
Out[10]:
'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 by modifying the input.
Alternatively, you can copy a cell (notice the Copy button -- 4th), paste it (5th button) and then make changes to the cell.

Guess what will happen below!

In [11]:
"111" + 10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-079358a118c7> in <module>()
----> 1 "111" + 10

TypeError: cannot concatenate 'str' and 'int' objects

How can you fix it?

In [12]:
# 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 [13]:
'111' * 5
Out[13]:
'111111111111111'

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? Try out what happens when you multiply two string values.

In [14]:
'cs' * '111'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-8212f0699c63> in <module>()
----> 1 'cs' * '111'

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

Variables [Slides 2-7, 8]

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

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

In [22]:
fav = 12

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

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

An example of doing string concatenation with variables.

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

Built-in Functions: max, min, type, len [Slides 2-9, 10, 11]

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

Finding a value type with the type function.

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

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

In [42]:
len('CS111')
Out[42]:
5
In [43]:
len('CS111 rocks!')  #try to guess before looking it up
Out[43]:
12
In [44]:
len('com' + 'puter') # the expression will be evaluated first, and then the result will be an argument for the function
Out[44]:
8
In [45]:
course = 'computer programming'
len(course)
Out[45]:
20
In [46]:
len(111)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-46-b21177f7b971> in <module>()
----> 1 len(111)

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

More built-in functions: Converting between types with str, int, and float. [Slides 2-12, 13, 14]

The function str

In [47]:
str(17) # convert an integer to string
Out[47]:
'17'
In [48]:
str(4.1) # convert a float to string
Out[48]:
'4.1'
In [49]:
'CS' + 111 # this generates an error, why?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-802a815d6daa> in <module>()
----> 1 'CS' + 111 # this generates an error, why?

TypeError: cannot concatenate 'str' and 'int' objects
In [50]:
'CS' + str(111) # this gives the desired output, why?
Out[50]:
'CS111'
In [51]:
len(str(111)) # does len(111) work? 
Out[51]:
3
In [52]:
len(str(min(17, 3))) # notice the nesting of many function calls. Which is the order of execution?
Out[52]:
1
In [53]:
lenOfName = len('CS' + str(max(110, 111))) # what is the result of this assignment?
In [54]:
str(lenOfName) # what is the output?
Out[54]:
'5'
In [55]:
str("CS11") # what is the output?
Out[55]:
'CS11'

The function int

In [56]:
int('42') # convert a string value to integer
Out[56]:
42
In [57]:
int('-273') # it works for negative numbers too
Out[57]:
-273
In [58]:
123 + '42' # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-58-f415c0b79b38> 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 [59]:
123 + int('42')
Out[59]:
165
In [60]:
int('3.141') # will this work? 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-60-d87ae886fbed> in <module>()
----> 1 int('3.141') # will this work?

ValueError: invalid literal for int() with base 10: '3.141'
In [61]:
int('five') # will this work?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-61-3459bad50246> in <module>()
----> 1 int('five') # will this work?

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

The function float

In [65]:
float('3.141') # convert a string value into a float value
Out[65]:
3.141
In [66]:
float('-273.15') # it works for negative values too
Out[66]:
-273.15
In [67]:
float('3') # can you guess the output, why?
Out[67]:
3.0
In [68]:
float('3.1.4') # what is the output for this?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-68-8884d5ff4a3d> in <module>()
----> 1 float('3.1.4') # what is the output for this?

ValueError: invalid literal for float(): 3.1.4
In [69]:
float('pi') # what is the output for this?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-69-24e0fdd361cd> in <module>()
----> 1 float('pi') # what is the output for this?

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

Dealing with float values [Slide 2-15]

The unexpected behavior of float values.

In [71]:
2.1 - 2.0 # what is the output value?
Out[71]:
0.10000000000000009
In [72]:
2.2 - 2.0
Out[72]:
0.20000000000000018
In [73]:
2.3 - 2.0
Out[73]:
0.2999999999999998
In [74]:
1.3 - 1.0
Out[74]:
0.30000000000000004
In [75]:
100.3 - 100.0
Out[75]:
0.29999999999999716
In [76]:
10.0/3.0
Out[76]:
3.3333333333333335
In [77]:
1.414*(3.14159/1.414)
Out[77]:
3.1415900000000003

Fixing the behavior with round [Slide 2-16]

In [78]:
round(3.14156)  # round the value to the float of the closest integer
Out[78]:
3.0
In [79]:
round(98.6) # round to the float of the closest integer
Out[79]:
99.0

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 [80]:
round(3.14156, 2)
Out[80]:
3.14
In [81]:
round(3.14156, 1)
Out[81]:
3.1
In [82]:
round(3.14156, 0)
Out[82]:
3.0
In [83]:
# round will round up if next digit is 5 or more
round(3.14156, 4)
Out[83]:
3.1416
In [84]:
round(2.3 - 2.0, 1) # what will the result be this time?
Out[84]:
0.3

The useful print function [Slide 2-17]

This function will display characters on the screen. It doesn't output a value like the other functions.
Notice how we will not see the output fields labeled with Out[] when we use print.

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

Special Case of using print without parantheses

In [91]:
print 1 + 2, 6 * 7, 'foo' + 'bar' # print is *special*. It doesn't need the parentheses. Only print is like that!
3 42 foobar

Expression values vs. print [Slide 2-19]

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 [92]:
max(10, 20)
Out[92]:
20
In [93]:
print max(10, 20)
20
In [94]:
10 + 20
Out[94]:
30
In [95]:
print (10 + 20)
30
In [96]:
message = "Welcome to CS 111" 

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

In [97]:
message
Out[97]:
'Welcome to CS 111'
In [98]:
print(message)
Welcome to CS 111

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

Building interactive programs with raw_input [Slide 2-20]

In [99]:
raw_input('Enter your name: ') # waits for user to provide an input value and then outputs the entry
Enter your name: Wendy
Out[99]:
'Wendy'
In [100]:
age = raw_input('Enter a number: ')  # we can store the entered input into a variable
Enter a number: 27.5
In [101]:
age # what value is stored and of what type?
Out[101]:
'27.5'
In [102]:
age + 4.0 # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-102-8beccef6f8b3> in <module>()
----> 1 age + 4.0 # will this work?

TypeError: cannot concatenate 'str' and 'float' objects
In [103]:
age = float(raw_input('Enter a number: ')) # perform conversion before storing the value
Enter a number: 27.5
In [104]:
age + 4.0 # will this work now?
Out[104]:
31.5

Error Types and Messages [Slide 2-22]

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

In [105]:
first-name = "Harry"
  File "<ipython-input-105-da86a8a1f9b5>", line 1
    first-name = "Harry"
SyntaxError: can't assign to operator
In [106]:
"CS" + 111
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-106-eca655dd05d0> in <module>()
----> 1 "CS" + 111

TypeError: cannot concatenate 'str' and 'int' objects
In [107]:
2017 + "'s record"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-107-ffe047861de7> in <module>()
----> 1 2017 + "'s record"

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [108]:
year = 2017
len(year)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-108-908d9565b7c9> in <module>()
      1 year = 2017
----> 2 len(year)

TypeError: object of type 'int' has no len()
In [109]:
month + 1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-109-e45e5ff84a8f> in <module>()
----> 1 month + 1

NameError: name 'month' is not defined
In [110]:
float("e")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-110-13ce1addddd1> in <module>()
----> 1 float("e")

ValueError: could not convert string to float: e
In [111]:
int('2.7182')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-111-6cc96bb71f63> in <module>()
----> 1 int('2.7182')

ValueError: invalid literal for int() with base 10: '2.7182'

Test your knowledge [Slide 2-23]

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

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