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.
max
, min
, type
, len
str
, int
, and float
float
valuesprint
functionThe 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.
3 + 4 * 5 # precedence
(3 + 4) * 5 # override precedence
3 + 4 * 5 # spaces don't matter
17/3 # floating point (decimal) division
17//3 # integer division
17 % 3 # integer remainder (% in this case is known as the modulo operator)
17.0//3 # result of // is a float if either operand is a float.
17//2.5
17%2.5
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)
.
5 + (12 - 7) * 4
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.
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.
"CS 111" # the string is within double quotes
'rocks!' # we can also use single quotes, it is still a string
"CS 111" + 'rocks!' # example of concatenation
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.
Solutions:
"CS 111 " + 'rocks!'
"CS 111" + ' rocks!'
"CS 111" + " " + 'rocks!'
Guess what will happen below:
"111" + 10
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?
# 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!
'123' * 4
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.
'cs' * '111'
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”!
fav = 17 # an assignment statement has no output
fav # this is called "variable reference" and denotes the current value of the variable
fav + fav # this is a simple expression that uses the current value of the variable
lucky = 8
fav + lucky
aSum = fav + lucky # define a new variable and assign to it the value returned by the expression on the right
aSum * aSum
Let us change the value stored in the variable named fav
.
fav = 11
Will this change affect the variable aSum?
How would you check that?
# No, assigning to fav does *not* change the values of previous assignments, other than to fav
# We can check by evaluating aSum:
aSum
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?
fav
An example of doing string concatenation with variables.
name = 'CS111'
name * fav # notice that we can have multiple lines of code in a single cell.
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.
min(7, 3)
max(7, 3)
min(7, 3, 2, 9) # notice how we can have as many arguments we want.
smallest = min(-5, 2) # variable smallest gets the output from the function, in this case, -5.
smallest # check the value stored in smallest
largest = max(-3, -10) # variable largest gets the value -3, which is the output of
# the function call with the arguments -3 and -10
largest #check the value stored in largest
max(smallest, largest, -1) # we can mix variables and values as function arguments
Finding the type of a value with the type
function.
type(111) # this is an integer value
type(4.0) # this is a decimal value, also known as a floating point number (because the decimal point can "float")
type("CS111") # this is a string value
type(max(7.3, 4)) # notice how we can nest function calls within each-other
x = "CS111 " + "rocks!"
type(x) # we can also ask for the type of variables, the same way as for values.
# Hey, what's the type of a type like int, float, str?
type(int)
# And what's the type of type?
type(type)
The function len
that returns the number of characters in a string.
len('CS111')
len('CS111 rocks!') #try to guess before looking it up
len('com' + 'puter') # the expression will be evaluated first, and then the result will be an argument for the function
course = 'computer programming'
len(course)
len(111)
str(17) # convert an integer to string
str(4.1) # convert a float to string
'CS' + 111 # this generates an error, why?
'CS' + str(111) # this gives the desired output, why?
len(str(111)) # does len(111) work?
lenOfName = len('CS' + str(max(110, 111))) # what is the result of this assignment?
str(lenOfName) # what is the output?
str("CS11") # what is the output?
len(str(min(17, 3))) # notice the nesting of many function calls. Which is the order of execution?
str((3 + 4) * len('C' + 'S' + str(max(110, 111)))) # See slide 20 for how this is evaluated
int
¶int('42') # convert a string value to integer
int('-273') # it works for negative numbers too
123 + '42' # will this work?
int
function?¶123 + int('42')
int('3.141') # will this work?
int('five') # will this work?
int(98.6) # convert from float to integer
int(-2.978) # what will this output?
int(422) # what will this output?
float
¶float('3.141') # convert a string value into a float value
float('-273.15') # it works for negative values too
float('3') # can you guess the output, why?
float('3.1.4') # what is the output for this?
float('pi') # what is the output for this?
float(42) # convert from an integer to float
float
values¶The unexpected behavior of float values.
2.1 - 2.0 # what is the output value?
2.2 - 2.0
2.3 - 2.0
1.3 - 1.0
100.3 - 100.0
10/3
1.414*(3.14159/1.414)
round
¶round(3.14156) # round the value to the closest integer
round(98.6) # round to the closest integer
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.
round(3.14156, 2)
round(3.14156, 1)
round(3.14156, 0)
# round will round up if next digit is 5 or more
round(3.14156, 4)
round(2.3 - 2.0, 1) # what will the result be this time?
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
.
print(7)
print('CS111')
print('CS' + str(111)) # it prints the result of the expression
print(len(str('CS111')) * min(17,3)) # notice the nested functions. What will the displayed?
college = 'Wellesley'
print('I go to ' + college) # expressions can combine values and variables
dollars = 10
print('The movie costs $' + str(dollars) + '.') # concatenation of string values
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.
print('a\nbc\ndef')
len('a\nbc\ndef') # \n counts as a single character
When print
is called with multiple arguments, it prints them all, separated by spaces.
print(1 + 2, 6 * 7, 'CS' + '111')
print(6,'*',7,'=',6*7)
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:
print(str(6) + ' * ' + str(7) + ' = ' + str(6*7))
The default space printed between multiple arguments to print
can be changed by the optional keyword argument sep=
string
print(6,'*',7,'=',6*7, sep='$') # separate printed values by dollar signs
print(6,'*',7,'=',6*7, sep=', ') # separate printed values by a comma and space
print(6,'*',7,'=',6*7, sep='') # separate printed values by zero characters (the empty string)
print(6,'*',7,'=',6*7, sep='\n') # separate printed values newlines
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.
max(10, 20)
print(max(10, 20))
10 + 20
print (10 + 20)
message = "Welcome to CS 111"
Question: why don't we see anything after executing the above cell?
message
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 (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:
str(print('Hi!'))
print(print(6*7))
type(print(print('CS'), print(111))) # Explain why each result line is the way it is!
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.
input('Enter your name: ') # waits for user to provide an input value and then outputs the entry
age = input('Enter your age: ') # we can store the entered input into a variable
age # what value is stored and of what type?
age + 4 # will this work?
age = float(input('Enter your age: ')) # perform conversion before storing the value
age + 2 # will this work now?
Try to guess what error type and message will appear in the examples below:
"CS" + 111
2017 + "'s record"
year = 2017
len(year)
month + 1
float("e")
int('2.7182')
first-name = "Harry" # variable names can't include hyphens, which look to Python like a minus operator
# use underscores instead, as in first_name
1 + age = 17 # Can't assign to the result of an addition operator.
1 + (age = 17) # Can't add a number and an assignment statement,
# because an assignment statement doesn't denote a values
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.