CS134: Introduction to the Python Language

Acknowlegement: This notebook has been adapted adapted from the Wellesley CS111 Spring 2019 course materials (http://cs111.wellesley.edu/spring19).

Examples to get started in Python.

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

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 # parenthesis can be used to 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 [ ]:
 

Summary: The results of an operator can 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/2. Make sure to understand what is the expected value type for a simple expression.

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 [10]:
"CS 134" # the string is within double quotes
Out[10]:
'CS 134'
In [11]:
'rocks!' # we can also use single quotes, it is still a string
Out[11]:
'rocks!'
In [13]:
"CS 134" + ' rocks!' # example of concatenation
Out[13]:
'CS 134 rocks!'

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?

Guess what will happen below:

In [15]:
"111" + '10'
Out[15]:
'11110'

This is 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.

How can you fix it?

In [ ]:
 

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' * '134'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-764185bede7a> in <module>
----> 1 'cs' * '134'

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

Variables

A variable is essentially a box or placeholder containing a value that a programmer names or changes with an assignment statement, using =.
Variables can name any value.
Important: The symbol = is referred to as “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 = 12

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

Built-in Functions: print, input, type, int, str, float

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

The input function is used to take input from the user. By default, input value is always of type string. We can use built-in functions int and float to convert the inputed value to the desired type.

In [29]:
print(7)
7
In [30]:
print('Welcome to CS134')
Welcome to CS134

Using the built-in str function

In [31]:
type(134)
Out[31]:
int
In [32]:
'CS' + 134
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-1f4dda38b057> in <module>
----> 1 'CS' + 134

TypeError: must be str, not int
In [33]:
"CS" + '134'
Out[33]:
'CS134'
In [34]:
'CS' + str(134)
Out[34]:
'CS134'
In [35]:
course_num = 134
In [36]:
"CS" + str(course_num)
Out[36]:
'CS134'
In [37]:
print('CS' + str(134)) # it prints the result of the expression
CS134
In [38]:
college = 'Williams'
print('I go to ' + college) # expressions can combine values and variables
I go to Williams
In [40]:
college = 'Williams'
print('I go to', college) # expressions can combine values and variables
I go to Williams
In [39]:
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 [ ]:
print(1 + 2, 6 * 7, 'CS' + '111') 
In [ ]:
print(1,'+',2,'=',1+2)

Building interactive programs with input

In [41]:
input('Enter your name: ') # waits for user to provide an input value and then outputs the entry
Enter your name: Harry Potter
Out[41]:
'Harry Potter'
In [42]:
age = input('Enter your age: ')  # we can store the entered input into a variable
Enter your age: 17
In [43]:
age # what value is stored and of what type?
Out[43]:
'17'
In [44]:
type(age)
Out[44]:
str
In [45]:
age + 4 # will this work?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-8205a21f668a> in <module>
----> 1 age + 4 # will this work?

TypeError: must be str, not int
In [46]:
age = int(input('Enter your age: ')) # perform conversion before storing the value
Enter your age: 17
In [47]:
age + 4 # will this work now?
Out[47]:
21

Detour: the type function

In [ ]:
type(134) # 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("CS134") # this is a string value
In [ ]:
x = "CS134 " + "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)

Detour: the int function

In [ ]:
int('42') # convert a string value to integer
In [ ]:
int('-273') # it works for negative numbers too
In [ ]:
123 + int('42')  # will this work?
In [ ]:
int('3.141') # will this work? 
In [ ]:
int('five') # will this work?
In [ ]:
int(98.6) # convert from float to integer
In [ ]:
int(-2.978) # what will this output?
In [ ]:
int(422) # what will this output?
In [ ]:
64 - 4*12*1

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 [ ]:
20//2
In [ ]:
print(20//2)
In [ ]:
10 + 20
In [ ]:
print (10 + 20)
In [ ]:
message = "Welcome to CS 134" 

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

In [ ]:
message
In [ ]:
print(message)

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, Canopy 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:

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

Error Types and Messages

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

In [ ]:
"CS" + 134
In [ ]:
2017 + "'s record"
In [ ]:
year = 2017
len(year)
In [ ]:
month + 1
In [ ]:
float("e")
In [ ]:
int('2.7182')
In [ ]:
first-name = "Harry" # variable names can't include hyphens, which look to Python like a minus operator
                     # use underscores instead, as in first_name
In [ ]:
1 + age = 17 # Can't assign to the result of an addition operator.
In [ ]:
1 + (age = 17) # Can't add a number and an assignment statement, 
               # because an assignment statement doesn't denote a values

[Extra] Misc. Built-in Functions: float, max, min, len

Play with other built-in functions provided by python below.

The function float

In [ ]:
float('3.141') # convert a string value into a float value
In [ ]:
float('-273.15') # it works for negative values too
In [ ]:
float('3') # can you guess the output, why?
In [ ]:
float('3.1.4') # what is the output for this?
In [ ]:
float('pi') # what is the output for this?
In [ ]:
float(42)   # convert from an integer to float

The function max, min

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 [ ]:
largest #check the value stored in largest
In [ ]:
max(smallest, largest, -1) # we can mix variables and values as function arguments

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

In [ ]:
len('CS134')
In [ ]:
len('CS134 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(134)