# 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 :
3 + 4 * 5 # precedence

Out:
23
In :
(3 + 4) * 5 # override precedence

Out:
35
In :
3 + 4 * 5 # spaces don't matter

Out:
23
In :
17/3 # floating point (decimal) division

Out:
5.666666666666667
In :
17//3 # integer division

Out:
5
In :
17 % 3 # integer remainder (% in this case is known as the modulo operator)

Out:
2
In :
17.0//3 # result of // is a float if either operand is a float.

Out:
5.0
In :
17//2.5

Out:
6.0
In :
17%2.5

Out:
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 :
5 + (12 - 7) * 4

Out:
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 :
"CS 111" # the string is within double quotes

Out:
'CS 111'
In :
'rocks!' # we can also use single quotes, it is still a string

Out:
'rocks!'
In :
"CS 111" + 'rocks!' # example of concatenation

Out:
'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 :
"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 :
'123' * 4

Out:
'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 :
'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 :
fav = 17 # an assignment statement has no output

In :
fav # this is called "variable reference" and denotes the current value of the variable

Out:
17
In :
fav + fav # this is a simple expression that uses the current value of the variable

Out:
34
In :
lucky = 8

In :
fav + lucky

Out:
25
In :
aSum = fav + lucky # define a new variable and assign to it the value returned by the expression on the right

In :
aSum * aSum

Out:
625

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

Out:
25
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

Out:
4

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.

Out:
'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 :
min(7, 3)

Out:
3
In :
max(7, 3)

Out:
7
In :
min(7, 3, 2, 9) # notice how we can have as many arguments we want.

Out:
2
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

Out:
-5
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

Out:
-3
In :
max(smallest, largest, -1) # we can mix variables and values as function arguments

Out:
-1

Finding the type of a value with the type function.

In :
type(111) # this is an integer value

Out:
int
In :
type(4.0) # this is a decimal value, also known as a floating point number (because the decimal point can "float")

Out:
float
In :
type("CS111") # this is a string value

Out:
str
In :
type(max(7.3, 4)) # notice how we can nest function calls within each-other

Out:
float
In :
x = "CS111 " + "rocks!"
type(x) # we can also ask for the type of variables, the same way as for values.

Out:
str
In :
# Hey, what's the type of a type like int, float, str?
type(int)

Out:
type
In :
# And what's the type of type?
type(type)

Out:
type

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

In :
len('CS111')

Out:
5
In :
len('CS111 rocks!')  #try to guess before looking it up

Out:
12
In :
len('com' + 'puter') # the expression will be evaluated first, and then the result will be an argument for the function

Out:
8
In :
course = 'computer programming'
len(course)

Out:
20
In :
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 :
str(17) # convert an integer to string

Out:
'17'
In :
str(4.1) # convert a float to string

Out:
'4.1'
In :
'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 :
'CS' + str(111) # this gives the desired output, why?

Out:
'CS111'
In :
len(str(111)) # does len(111) work?

Out:
3
In :
lenOfName = len('CS' + str(max(110, 111))) # what is the result of this assignment?

In :
str(lenOfName) # what is the output?

Out:
'5'
In :
str("CS11") # what is the output?

Out:
'CS11'
In :
len(str(min(17, 3))) # notice the nesting of many function calls. Which is the order of execution?

Out:
1
In :
str((3 + 4) * len('C' + 'S' + str(max(110, 111)))) # See slide 18 for how this is evaluated

Out:
'35'

#### The function int¶

In :
int('42') # convert a string value to integer

Out:
42
In :
int('-273') # it works for negative numbers too

Out:
-273
In :
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 :
123 + int('42')

Out:
165
In :
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 :
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 :
int(98.6) # convert from float to integer

Out:
98
In :
int(-2.978) # what will this output?

Out:
-2
In :
int(422) # what will this output?

Out:
422

#### The function float¶

In :
float('3.141') # convert a string value into a float value

Out:
3.141
In :
float('-273.15') # it works for negative values too

Out:
-273.15
In :
float('3') # can you guess the output, why?

Out:
3.0
In :
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 :
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 :
float(42)   # convert from an integer to float

Out:
42.0

## 6. Dealing with float values¶

The unexpected behavior of float values.

In :
2.1 - 2.0 # what is the output value?

Out:
0.10000000000000009
In :
2.2 - 2.0

Out:
0.20000000000000018
In :
2.3 - 2.0

Out:
0.2999999999999998
In :
1.3 - 1.0

Out:
0.30000000000000004
In :
100.3 - 100.0

Out:
0.29999999999999716
In :
10/3

Out:
3.3333333333333335
In :
1.414*(3.14159/1.414)

Out:
3.1415900000000003

### Fixing the behavior with round¶

In :
round(3.14156)  # round the value to the closest integer

Out:
3
In :
round(98.6) # round to the closest integer

Out:
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 :
round(3.14156, 2)

Out:
3.14
In :
round(3.14156, 1)

Out:
3.1
In :
round(3.14156, 0)

Out:
3.0
In :
# round will round up if next digit is 5 or more
round(3.14156, 4)

Out:
3.1416
In :
round(2.3 - 2.0, 1) # what will the result be this time?

Out:
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 :
print(7)

7

In :
print('CS111')

CS111

In :
print('CS' + str(111)) # it prints the result of the expression

CS111

In :
print(len(str('CS111')) * min(17,3)) # notice the nested functions. What will the displayed?

15

In :
college = 'Wellesley'
print('I go to ' + college) # expressions can combine values and variables

I go to Wellesley

In :
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')

3 42 CS111

In :
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 :
print(1,'+',2,'=',1+2, sep='||') # separate printed values by two vertical bars

1||+||2||=||3

In :
print(1,'+',2,'=',1+2, sep=', ') # separate printed values by a comma and space

1, +, 2, =, 3

In :
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 :
print('a\nbc\ndef')

a
bc
def

In :
len('a\nbc\ndef') # \n counts as a single character

Out:
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 :
max(10, 20)

Out:
20
In :
print(max(10, 20))

20

In :
10 + 20

Out:
30
In :
print (10 + 20)

30

In :
message = "Welcome to CS 111"


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

In :
message

Out:
'Welcome to CS 111'
In :
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 :
str(print(print('CS'), print(111))) # Explain why each result line is the way it is!

CS
111
None None

Out:
'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 :
input('Enter your name: ') # waits for user to provide an input value and then outputs the entry

Enter your name: Olivia

Out:
'Olivia'
In :
age = input('Enter your age: ')  # we can store the entered input into a variable

Enter your age: 18

In :
age # what value is stored and of what type?

Out:
'18'
In :
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 :
age = float(input('Enter your age: ')) # perform conversion before storing the value

Enter your age: 18

In :
age + 4 # will this work now?

Out:
22.0

## 9. Error Types and Messages¶

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

In :
"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 :
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 :
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 :
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 :
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 :
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 :
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 :
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 :
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


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 :
# You write:
x = 5 + 6

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

Success!


Compute 7 plus 15 and put it in the variable y

In :
# Your code here:
y = 7 + 15

In :
assert y == 22
print('Success!')

Success!


Compute 15 times 5 and put it in the variable z

In :
# Your code here:
z = 15 * 5

In :
assert z == 75
print('Success!')

Success!


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

In :
# Your code here:
a = 15 % 5

In :
assert a == 0
print('Success!')

Success!


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

In :
# Your code here:
h = 34 % 3

In :
assert h == 1
print('Success!')

Success!


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

In :
# Your code here:
b = 6 / 12

In :
assert b == 0.5
print('Success!')

Success!


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

In :
# Your code here:
c = 'arbitrary' + 'string'

In :
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 :
# Your code here:
d = 1000 * 'q'

In :
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 :
length = 5
width = 7.5

area = length * width

In :
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 :
import math


In :
assert area == 167.41547250980008
print('Success!')

Success!


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

In :
s = '15'

intified = int(s)

In :
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 :
s = '19.2'

floating = float(s)

In :
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 :
s1 = 'I am '
s2 = ' years old'
age = 1000

claim = s1 + str(age) + s2

In :
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 :
s1 = 'I have '
s2 = ' pizzas'
p1 = 400
p2 = 556


assert claim == 'I have 956 pizzas'

Success!