0% found this document useful (0 votes)
77 views

Topic2 Variables Expression Statements

This document introduces variables, expressions, and statements in Python. It discusses basic data types like integers, floats, booleans, and strings. It explains how the Python interpreter processes code and provides examples of literals, variables, and naming conventions for variables. The goal is to help students understand these core programming concepts and "think like the Python interpreter".

Uploaded by

Hikari Aoi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Topic2 Variables Expression Statements

This document introduces variables, expressions, and statements in Python. It discusses basic data types like integers, floats, booleans, and strings. It explains how the Python interpreter processes code and provides examples of literals, variables, and naming conventions for variables. The goal is to help students understand these core programming concepts and "think like the Python interpreter".

Uploaded by

Hikari Aoi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

EECS 1015

Introduction to Computer Science and Programming

Topic 2
Variables, Expressions, and Statements

Fall 2021
Michael S. Brown
EECS Department
York University

EECS1015 – York University -- Prof. Michael S. Brown 1


Goals of this Lecture
• To help you understand variables, expression and statements

• Discuss basic data types in Python: Integer, Floats, Boolean, Strings

• To help you start "thinking" like the Python interpreter

• To see how to get input from the user

EECS1015 – York University -- Prof. Michael S. Brown 2


Code and the Python Interpreter

Output of running
Python Interpreter program
lda 10 r1
lda 20 r2
add r1 r2 15
sto 21 20
out
dat 5 ..
data 10

x = 5 Converts your Python code to


y = 10 + x code that run on your CPU.
z = x + y
print(z) The Python Interpreter is software that converts your
… python code into machine-level code that runs on your
computer. We can think of the interpreter as a program
that "runs" your code. It is important that you understand
how the interpreter processes your code. Being able to
"think like the interpreter" will help make you a better
programmer.
EECS1015 – York University -- Prof. Michael S. Brown 3
Part 1: Literals (Raw Data)

EECS1015 – York University -- Prof. Michael S. Brown 4


Literals
• When writing a program, you will often type in values such as
numbers and sequences of letters (called a string).
• Literals can be thought of raw data written by the programmer and
used by the program. I use the word "raw data" to distinguish it from
data computed by your program.
• See next slides for examples

EECS1015 – York University -- Prof. Michael S. Brown 5


Literal Example 1
Python code
print( "This is a literal" )
x = 5 + 5 All items shown in red are
print(x) considered literals.
print(10.5)

Python interpreter output


This is a literal
10
10.5

Try it in trinket https://trinket.io/python/52dba2d0c5

EECS1015 – York University -- Prof. Michael S. Brown 6


Numerical literals and String literals
• The two most common literals in Python
• Numerical literals (integers/floats)
• Numbers in python are categorized as integers and floats
• Integers are whole numbers: 0, 1, 100, -50, 2020
• Floats are numbers with a decimal point: 0.234, -10.3040, 2.5
• String literals
• A string is a sequence of characters surrounded by quotation marks
"This is a string"
"1234" This is not the number
A special string known as 1234, it is four characters
"" the empty string '1', '2', '3', '4'
"*Hel-lo*"
Strings don't have to be just letters and numbers, there can be other
characters.
EECS1015 – York University -- Prof. Michael S. Brown 7
Additional literal types
• The Boolean literal
• True and False are special literals in Python. These are known as
"booleans" and represent data that has only two values.

• The None literal


• The word None is also a special literal used in Python. It is used to specify a
special case when a variable has not been set to any data.

Important: When you use True, False, or None that the first letter is capitalized.
For example, False and FALSE are not the same, only False is the Boolean literal

EECS1015 – York University -- Prof. Michael S. Brown 8


Literal Example 2 – Boolean and None
Python code
x = True
z = False All items shown in red are
y = None considered literals.
print(x) There are not strings. Notice there is
print(y) no quotation mark. True, False, and
print(z) None are considered literals to Python.

Python interpreter output


True
None
False

Try it in trinket https://trinket.io/python/53d77ca940

EECS1015 – York University -- Prof. Michael S. Brown 9


Part 2: Variables and Name Binding

EECS1015 – York University -- Prof. Michael S. Brown 10


Variables
• We can think of variables a way to access and store data.

• Variables help the programmer manipulate data.

• A Python variables keeps track of three properties:


(1) The value of the data
(2) The type of data (integer, float, string, etc)
(3) The "ID" of the object (we will talk about this later)

EECS1015 – York University -- Prof. Michael S. Brown 11


Variables - Example 1
x = 5 Python code
y = 10
z = x+y All items shown in red are
firstName = "Abdel" variables.
lastName = "Zhang"
print(firstName)
print(lastName)
print(x)
print(y)
print(z)

Python interpreter output


Abdel
Zhang
5
10
15
Try it in trinket https://trinket.io/python/b0f23ede52

EECS1015 – York University -- Prof. Michael S. Brown 12


Rules for valid variable names
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive
• For example: age, Age and AGE are three different variables

EECS1015 – York University -- Prof. Michael S. Brown 13


Getting use to "nerd" notations
• In computer science, you will often see that we like to use shortcuts
to describe data

• For example, in the previous slide you saw A-z which is a fast way of
saying all characters representing letters (upper case and lower
case). A-Z means only uppercase, a-z only lowercase, A-z means
all.

• Saying 0-9 means all numbers.

• So, variables can start with any character from (A-z, _ )

EECS1015 – York University -- Prof. Michael S. Brown 14


For those of you new to the English language
• What is a "nerd"?

• A nerd is a cool person who studies computer science!

EECS1015 – York University -- Prof. Michael S. Brown 15


Variable name examples
Valid variable names Invalid variable names
x 2Variable
y my var
myVar2 rpi-Square
__Name 1_1abc
This_is_a_long_variable_name a#b
Area $test
area_of_a_square test$
taxRate
universityName
Count

Python variable name rule:


starts with (A-z, _)
EECS1015 – York University -- Prof. Michael S. Brown
after start can only be (A-z, 0-9, _) 16
Variable naming
• In EECS1015, we will often use short and simple variable names as
examples, such as x, y, z.

• But as you learn to program, you should use descriptive variable


names that help describe the data
• For example, if a variable is used for someone's age, don't call it x, use the
variable name age, or personAge

• Some companies (e.g., Google) have strict rules on naming


variables – all employees must follow them. See link below:
https://google.github.io/styleguide/pyguide.html#316-naming

EECS1015 – York University -- Prof. Michael S. Brown 17


Thinking like the Python interpreter
• What if you typed in an invalid variable name?
When your interpreter first opens your program, it
print("Hello") OK
scans the entire program line by line. If it sees a line
x = 5 OK of code that violates one a rule (in this case the
2y = 5+5 NOT OK - error variable name), the interpreter will stop and give an
error message. This type of error is known as a
syntax error. Note: The error message may not tell
you exactly what the problem is, but it often will tell
you what line in the program the error occurs.

File "C:/Users/mbrown/PycharmProjects/pythonProject1/main.py", line 3


2y = 5+5
^
SyntaxError: invalid syntax Try it in trinket: https://trinket.io/python/2fac2db0fa

EECS1015 – York University -- Prof. Michael S. Brown 18


Syntax and syntax errors
• In computer science, the syntax of a computer language is the set of
rules that defines the combinations of symbols that are considered to
be correctly structured statements or expressions in that language.
If your program violates the rules, you will get a "syntax error".
You will hear this term "syntax error" often.

Most programming languages (Python included) will scan the program before running it to detect
any syntax errors. If it finds an error it will not run the program. The example on the previous slide
is a syntax error.

File "C:/Users/mbrown/PycharmProjects/pythonProject1/main.py", line 3


2y = 5+5
^
SyntaxError: invalid syntax

EECS1015 – York University -- Prof. Michael S. Brown 19


Thinking like the Python Interpreter (1/9)
These slides are to help you start "thinking" like your Python interpreter.

Let's consider the simple program below. Notice that I've added line numbers. Even though you
don't have to put in line numbers when you program, your interpreter keeps track of the line numbers
of your of code. Knowing the line number is useful when the interpreter tell you an error occurred at
a particular line of code.

1: x = 5
2: y = 10 + x
3: z = x + y
4: print(z)

EECS1015 – York University -- Prof. Michael S. Brown 20


Thinking like the Python Interpreter (2/9)
First, the interpreter will scan this entire program to make sure there are no
syntax errors. When the interpreter scans the program it sees several literals
(e.g. the values 5 and 10).
1: x = 5
2: y = 10 + x The interpreter will store these literals as data in memory (see below). Python
3: z = x + y refers to data as "objects". It also knows the type of these objects (e.g.,
4: print(z) integer, float, string, so on). The interpreter also sees several variables. It
keeps track of these variables (see below).

So, before the program even starts running, the interpreter has the following
information:

List of variables Data/Objects stored in memory


x 5 (integer)
y
10 (integer)
z

EECS1015 – York University -- Prof. Michael S. Brown 21


Thinking like the Python Interpreter (3/9)
After the program has been scanned, the interpreter starts to
run (or sometimes called "execute") the program. It does this
line by line:
1: x = 5
2: y = 10 + x First, line 1. x = 5
3: z = x + y
This line (or statement) means assign the value of 5, to the variable
4: print(z)
x. The "=" is known as the assignment operator.

This is known as "name binding". The object "5" is now


bound to variable x. An arrow shows the data x is bound to.

List of variables Data/Objects stored in memory


x 5 (integer)
y
10 (integer)
z

EECS1015 – York University -- Prof. Michael S. Brown 22


Thinking like the Python Interpreter (4/9)
After executing line 1, the interpreter moves to line 2.
Line 2. y = 10 + x
1: x = 5 This line is a bit more complicated. We see before the assignment operator,
2: y = 10 + x there is 10 + x. This is known as an expression. Python will evaluate (or compute)
3: z = x + y this expression before doing the assignment.
4: print(z)
Notice that the expression includes the bound variable "x". "x" is bound to
the object with value "5". So, when executing this expression, it will use the
data value at x.

See next slide.

List of variables Data/Objects stored in memory


x 5 (integer)
y
10 (integer)
z
EECS1015 – York University -- Prof. Michael S. Brown 23
Thinking like the Python Interpreter (5/9)
Breaking down line 2:
y = 10 + x

Step 1: handle the expression 10 + x


Step 2: replace the x with its bound value 5 10 + (5)
Step 3: compute the value of this math expression 15
Step 4: the result of step 3 will create a new object that is stored memory (see below)
Step 5: now we have y = 15
Step 5 will perform name binding and y now is bound to object 15

List of variables Data/Objects stored in memory


x 5 (integer)
y
10 (integer)
z 15 (integer)

EECS1015 – York University -- Prof. Michael S. Brown 24


Thinking like the Python Interpreter (6/9)
After executing line 2, the interpreter moves to line 3.
Line 3. z = x + y
1: x = 5 This line is almost identical to line 2. Except now, we have two variables
2: y = 10 + x in the expression x + y. Notice that both of these variables are already
3: z = x + y bound to objects. This line will execute just like line 2.
4: print(z)
See next slide.

List of variables Data/Objects stored in memory


x 5 (integer)
y
10 (integer)
z 15 (integer)
EECS1015 – York University -- Prof. Michael S. Brown 25
Thinking like the Python Interpreter (7/9)
Breaking down this line 3:
z = x + y

Step 1: handle the expression x+y


Step 2: replace x with its bound value (5) + y
Step 3: replace y with its bound value 5 + (15)
Step 4: compute the value of this math expression 20
Step 5: the result of step 5 is to create a new object and place it in memory (see below)
Step 6: Last set is the assignment of 20 to z z = 20
Step 6 will perform name binding and z now is bound to object 20

List of variables Data/Objects stored in memory


x 5 (integer)
y
10 (integer)
z 15 (integer)
20 (integer)
EECS1015 – York University -- Prof. Michael S. Brown 26
Thinking like the Python Interpreter (8/9)
After executing line 3, the interpreter now executes line 4.
Line 4. print(z)
1: x = 5
2: y = 10 + x The "print( )" is known as a function. We will talk about functions more later.
3: z = x + y Right now, this line means execute the print function by passing the
4: print(z) variable z to it. As you know, this will print the value of the object
that is bound to the variable z.

Output
20

List of variables Data/Objects stored in memory


x 5 (integer)
y
10 (integer)
z 15 (integer)

20 (integer)
EECS1015 – York University -- Prof. Michael S. Brown 27
Thinking like the Python Interpreter (9/9)
Before the program started
1: x = 5
2: y = 10 + x List of variables Data/Objects stored in memory
3: z = x + y x 5 (integer)
4: print(z)
y
10 (integer)

Before the program was even z


started, the interpreter had
already create objects/data in
While/after the program is running
memory based on literals in the
program. It also knew the name of all List of variables Data/Objects stored in memory
variables. x 5 (integer)
y
While the program ran (we call this 10 (integer)
run time), variables were bound to data.
z 15 (integer)
Also, in the case of y and z, the variables
were bound to new data that was
20 (integer)
created when the expressions
we evaluated.
EECS1015 – York University -- Prof. Michael S. Brown 28
Interpreter – Thinking step by step
• In our previous examples, the interpreter executed code one line at a time

• Everything was done "step by step"


• At no time was the interpreter doing multiple things. We could break down each
line of code into a step-by-step process.
• Some lines of codes involved multiple steps

• If you didn't watch it, please see the Lecture 1 on "How your computer
works". Step-by-step is how your computer works, even at the lowest
hardware level. As you learn to program, you need to learn to think about
solving problems and tasks in a step-by-step manner.

EECS1015 – York University -- Prof. Michael S. Brown 29


The "type" of a bound variable
Python code
x = 10
y = 2
z = 3.5 The type() function will return
print( type(x) ) the type of the variable. See below.
print( type(y) )
print( type(z) )

Python interpreter output


<class 'int'> Python3 calls the type a "class".
<class 'int'> We will talk about this more later.
<class 'float'> But you can see for each variable,
Python knows the type of data it is bound to.
'int' is short for integer

Try it in trinket https://trinket.io/python/79961c9f90

EECS1015 – York University -- Prof. Michael S. Brown 30


Using an unbound variable – Run-time error!
x=5
Consider this code:
y=20
In this case, we get an error when the print(z)
print(x)
is executed. This is because the variable z is
print(y)
not assigned (or bound) to any data.
print(z)

Notice this is different than the syntax error. The


syntax error was made by the interpreter before
any code was executed.
5
20 Here, the print(x) and print(y) perform correctly.
print(z) This error was caused when the line with print(z)
NameError: name 'z' is not defined was called. We call this a "run-time" error,
because it occurs when the program is running.

Try it in trinket https://trinket.io/python/e849fc9672

EECS1015 – York University -- Prof. Michael S. Brown 31


Fixing this with the None literal
x=5
y=20 Here we give the value of z to None.
z=None This means we haven't bound the
print(x) variable to any data.
print(y)
print(z)

5 In this case, we will not get an error. The print


20 statement will print out the None literal.
None

EECS1015 – York University -- Prof. Michael S. Brown 32


Part 3: Expressions, Statements,
Math Operators

EECS1015 – York University -- Prof. Michael S. Brown 33


Python expression and statements
• In our previous examples, we saw "expressions" and "statements"

z=x+y
The entire line is considered a statement.
Statements generally do not return a value. x + y is an expression.

We can also think of statements of performing An expression is a combination of values, variables,


some action. For example, this is an operators, and calls to functions.
assignment statement. After the statement
is complete, the variable z is bound to the Expressions need to be evaluated and will
result of the expression (x+y). return a value or new object.

See trinket code: https://trinket.io/python/07c636968f


EECS1015 – York University -- Prof. Michael S. Brown 34
Python expression and statements
• In our previous example, we saw "expressions" and "statements"

print( type(z) )
The entire line is considered a statement.
This line of code will call the function In this example, the call to the function type(z) is
type(z) first, the result of that function considered an expression, since the function returns
is passed to the function print( ). This a value.
will perform the action to print the result.
Remember: An expression is a combination
of values (literals), variables, operators, and
calls to functions.
Expressions need to be evaluated.

EECS1015 – York University -- Prof. Michael S. Brown 35


Math expressions
• Many of our expression in programming involve some simple math

• When you first learn a programming language, you need to learn the
symbols it uses for math

• Many languages are similar, e.g. multiple is always the * symbol,


divide is always the / symbol, and so on

EECS1015 – York University -- Prof. Michael S. Brown 36


Math operators in Python
Assume a = 10, b = 20
Operator Description Example
+ Addition - Adds values on either side of the a + b will give 30
operator
- Subtraction - Subtracts right hand operand a - b will give -10
from left hand operand
* Multiplication - Multiplies values on either a * b will give 200
side of the operator
/ Division - Divides left hand operand by right b / a will give 2.0
hand operand
% Modulus - Divides left hand operand by right b % a will give 0
hand operand and returns remainder
** Exponent - Performs exponential (power - 𝑥 𝑦 ) a**2 will give 100
calculation on operators. Format x**y.
// Floor Division - The division of operands 9//2 is equal to 4 and
where the result is the quotient in which the 9.0//2.0 is equal to 4.0
digits after the decimal point are removed.

EECS1015 – York University -- Prof. Michael S. Brown 37


Math operators you may not be familiar with
Modulus operator (%)
Remember when you first learned division with whole numbers, we had the
notion of "remainder"? Modulus computes the remainder.
3
3 10
9
1 3 cannot divide 1, so we say remainder 1.

How would we write the above? If division, we would write 10 / 3.


Modulus would be 10 % 3. So 10%3 is 1.

Other examples: 27 % 2 is 1 27 % 4 is 3 30 % 10 is 0 (why?)

EECS1015 – York University -- Prof. Michael S. Brown 38


Math operators you may not be familiar with
Floor division (//)
Remember when you first learned division with whole numbers, we had the
notion of a quotient (the part on top)? Floor division returns the quotient.
3 This would be the result of floor division.
3 10
9
1 3 cannot divide 1, so we say remainder 1.
How would we write the above?
Floor division uses two "//" - so, 10 // 3 is 3

Examples: 25 // 3 is 8 109 // 10 is 10 1 // 3 is 0 (why?)


For floating point, think of floor division as rounding down
the result of division.
9.1 / 3.3 is 2.757575…. 9.1 // 3.3 is 2.0
EECS1015 – York University -- Prof. Michael S. Brown 39
Math operators and data types
• It is important to note that math operators may result in different data
type.
• Pythons uses the following rules:
1) float to float math results in a float

2) float to integer math results in a float

3) integer to integer math results in a integer


• Except for the division operator, integer to integer division results a float

EECS1015 – York University -- Prof. Michael S. Brown 40


Math operator and types
• Float to float math (result is a float)
<float><math operator><float> Result: <float>
Examples: 10.0 ** 2.0 100.0 (float)
33.5 - 5.0 28.5 (float)
15.0 / 2.5 7.5 (float)

• Float and integer math (results in float)


<integer><math operator> <float> Result: <float>
<float> <math operator> <integer> <float>
Examples: 10 * 2.0 20.0 (float)
8.2 - 10 -1.8 (float)

EECS1015 – York University -- Prof. Michael S. Brown 41


Math operator and types
• Integer to integer math
<integer><math operator><integer> Result: <integer>
Examples: 10 ** 2 100 (integer)
33 + 5 38 (integer)
15 // 2 7 (integer)
7 * 3 21 (integer)
• Exception to this is division with integers
<integer><math operator: /><integer> Result: <float>
Examples: 10 / 2 5.0 (float)
31 / 3 10.333334 (float)

(see next slide)

EECS1015 – York University -- Prof. Michael S. Brown 42


Division / always returns a float
Python code
x = 8
y = 2
z = x / y The type() function will return
w = 8 // y the type of the variable. See below.
print( type(x) )
print( type(y) )
print( type(z) )
print( type(w) )

Python interpreter output


<class 'int'>
<class 'int'>
<class 'float'>
<class 'int'>

Try it in trinket https://trinket.io/python/2f7b2b2f11

EECS1015 – York University -- Prof. Michael S. Brown 43


Mathematical expression
• Order of precedence for math operators
(1) Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and
(1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute *
100) / 60: in this case, the parentheses don’t change the result, but they reinforce that the expression
in parentheses will be evaluated first.

(2) Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and
not 27. Can you explain why?

(3) Multiplication and both division operators have the same precedence, which is higher than
addition and subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4,
and 5-2*2 is 1, not 6.

(4) Operators with the same precedence are evaluated from left-to-right. In algebra we say they are
left-associative. So in the expression 6-3+2, the subtraction happens first, yielding 3. We then add 2
to get the result 5. If the operations had been evaluated from right to left, the result would have been
6-(3+2), which is 1.
EECS1015 – York University -- Prof. Michael S. Brown See more details here: link 44
Evaluating an expression
• An expression can consist of multiple expressions, each evaluates to
a single value.
an expression values Evaluation of this expression. . .

(72 – 32) / 10.0 * 5 (72 – 32) / 10.0 * 5


(1)

40 / 10.0 * 5
Remember, you interpreter does everything step-by-step. (2)
It can only run one math operator at a time.
So an expression above will be broken into several
4.0 *5
small expression and performed one at a time, combining (3)
the results to get the final value. 20.0
EECS1015 – York University -- Prof. Michael S. Brown 45
Some more examples
Expression: 5 + 6 ** 2 - 10
5 + 6 ** 2 - 10 Exponent higher precedence than +/-
5 + 36 - 10 +- are equal, so evaluate left to right
41 - 10 last one
31 final result

Expression: (4 + 2) ** 2 / 3
(4 + 2) ** 2 / 3 Parenthesis has highest precedence
6 ** 2 / 3 Exponent has higher precendence than /
36 / 3 last one
12.0 final result – notice it is a float because of the divide

EECS1015 – York University -- Prof. Michael S. Brown 46


Even more examples
Expression: 36 / 3 * 2
36 / 3 * 2 / * have the same precendence, so left to right
12.0 *2 Notice result is float from last operation. Now multiple by 2.
24.0 final result is float

This would be a more clear expression: (36/3)*2

Expression: 10**(2+1)*2
10** (2+1) *2 Parenthesis has highest precedence
10**3*2 Exponent has higher precendence than /
1000 * 2 last one

2000 final result

This would be a more clear expression: (10**(2+1))*2

EECS1015 – York University -- Prof. Michael S. Brown 47


Math expressions with variables
• We typically write math expressions using variables

• Here is simple code to compute the price of an item after a discount


A 20% discount means we would
itemPrice = 8.50 multiple the price of an item by 0.8 to
discountAmount = 0.2 get it new price. Here we represent
newPrice = (1.0-discountAmount) * itemPrice the discount by a float.
print("Original Price")
print(itemPrice)
print("Discount Price") To compute the new amount, we need
print(newPrice) first compute the amount for the new
price (1-discount) then multiple that by
https://trinket.io/python/276609166d the item's price.

EECS1015 – York University -- Prof. Michael S. Brown 48


Math expression with variables diameter (d)

• Another example, computing the area of a pizza radius (r)

• I'll use the formula of the area of a circle: 𝐴 = 𝜋𝑟 2


• Pizzas are sold by the diameter, 𝑑, where 𝑑 = 2𝑟 (the diameter is two times
the radius).
pizzaSize = 12.0
pizzaArea = 3.141 * (pizzaSize / 2)**2
print("Size of pizza:")
print(pizzaSize)
print("Area of pizza:")
print(pizzaArea)
https://trinket.io/python/edebf3b948

EECS1015 – York University -- Prof. Michael S. Brown 49


Last example, Fahrenheit to Celsius
• In Canada, temperature is reported in Celsius (C)
• In the US, they still use Fahrenheit
• How to convert from F to C?
• Subtract 32 from F, then multiply by 5, then divide by 9
tempF=78.0
tempC=((tempF - 32) *5)/ 9 Deduct 32 from F, then multiply by 5,
print("Temp in F:") then divide by 9.
print(tempF)
print("Temp in C:")
print(tempC)
https://trinket.io/python/822e1d7bc9
Try it here. If you want to verify if it is correct, 212F is 100C.

EECS1015 – York University -- Prof. Michael S. Brown 50


Make sure to match your () correctly
• When you first start programming, it can be easy to make simple
mistakes
• For example, what if we had an extra ) in the last code.

tempF=78.0 Do you see the mistake?


tempC=((tempF - 32)) *5)/ 9 It can be hard to find?
print("Temp in F:")
print(tempF) You will spend many, many hours as a programmer
print("Temp in C:") searching for a missing or extra symbol.
print(tempC)

EECS1015 – York University -- Prof. Michael S. Brown 51


Make sure to match your () correctly
• When you first start programming, it can be easy to make simple
mistakes
• For example, what if we had an extra ) in the last code.
When you try to run PyCharm, you will get a Syntax
tempF=78.0 error, just like when we had a bad variable name.
tempC=((tempF - 32)) *5)/ 9
print("Temp in F:") Note that your Pycharm IDE will help you
print(tempF) with this, by highlighting parenthesis as you type:
print("Temp in C:")
print(tempC)
The mistake is actually here. I didn't mean to
put a ) here. Because I did, now the ) after
"5" is incorrect.

EECS1015 – York University -- Prof. Michael S. Brown 52


Mathematical operators shortcuts
Applying an operator to a variable and This operation is so common that most
reassigning result back to variable. programming languages have a "shortcut" for this.

a = a + b a += b

a = a - b a -= b

a = a * b a *= b

a = a / b shortcut syntax a /= b

a = a // b a //= b

a = a % b a %= b

EECS1015 – York University -- Prof. Michael S. Brown https://trinket.io/library/trinkets/77edae8da8 53


Part 4: Reassigning Variables

EECS1015 – York University -- Prof. Michael S. Brown 54


Reassigning variables (think like the interpreter)
Before the program starts, our interpreter has made a pass
1: x = 5 through the entire program and has already stored the literals,
2: y = 10 and made a list of the variables.
3: x = x + y
3: y = x List of variables Data/Objects stored in memory
4: print(x) x 5 (integer)
5: print(y)
y
10 (integer)

Let's consider this code.


Notice here that x and y
are assigned (or bound)
multiple times.

EECS1015 – York University -- Prof. Michael S. Brown 55


Reassigning variables (1/5)
Line 1: The statement binds the variable x to the value 5.
1: x = 5
2: y = 10
3: x = x + y
3: y = x List of variables Data/Objects stored in memory
4: print(x) x 5 (integer)
5: print(y)
y
10 (integer)

EECS1015 – York University -- Prof. Michael S. Brown 56


Reassigning variables (2/5)
Line 2: The statement binds the variable y to the value 10.
1: x = 5
2: y = 10
3: x = x + y
4: y = x List of variables Data/Objects stored in memory
5: print(x) x 5 (integer)
6: print(y)
y
10 (integer)

EECS1015 – York University -- Prof. Michael S. Brown 57


Reassigning variables (3/5)
Line 3: Has to evaluate the expression (x+y) then assign to x.
1: x = 5 We can think of x as being "reassigned" to a new object.
2: y = 10
3: x = x + y
4: y = x List of variables Data/Objects stored in memory
5: print(x) x step 2
5 (integer)
6: print(y)
y
10 (integer)
step 5
15 (integer)

Think like the interpreter x=x+y step 1: evaluate the expression x + y


step-by-step:
5+y step 2: replace x with its bound value

5 + 10 step 3: replace y with its bound value

15 step 4: compute 5+10 and place this in memory


x = 15 step 5: bound x to the new object/data 15

EECS1015 – York University -- Prof. Michael S. Brown 58


Reassigning variables (4/5)
Line 4: We bind y to the same object that x is bound to.
1: x = 5 Note, y does not refer to "x", it refers to the object 15.
2: y = 10
Correct interpretation
3: x = x + y
4: y = x List of variables Data/Objects stored in memory
5: print(x) x
6: print(y) 5 (integer)

10 (integer)
y
15 (integer)

Incorrect interpretation
List of variables Data/Objects stored in memory
x 5 (integer)

10 (integer)
y
15 (integer)
EECS1015 – York University -- Prof. Michael S. Brown 59
Reassigning variables (5/5)
Lines 5&6: The next two lines of code print the data
1: x = 5 bound to x and y. Note that this is the exact same data!
2: y = 10
Correct interpretation
3: x = x + y
4: y = x List of variables Data/Objects stored in memory
5: print(x) x
6: print(y) 5 (integer)

10 (integer)
y
15 (integer)

Note: After this code, the values of "5" and "10" are unbound. This means we no longer have a way
in our code to access the data 5 and 10 through variables.

EECS1015 – York University -- Prof. Michael S. Brown 60


Swapping values between two variables
Python code
a = 5
b = 10 We want to swap data between variables a and b.
a = b Initially we have a=5 and b=10. We want a=10 and
b = a b=5. Will this work?
print(a)
print(b) Why not?

Python interpreter output


10
10
Both values are 10. What is going on?

Try it in trinket https://trinket.io/python/fc6809d587

EECS1015 – York University -- Prof. Michael S. Brown 61


Swap – Think like the interpreter (1/2)
Before program runs, Python interpreter already has this determined.

a = 5 List of variables Data/Objects stored in memory


b = 10 a 5 (integer)
a = b b
b = a 10 (integer)

line 1 – bind a to 5
a = 5 List of variables Data/Objects stored in memory
b = 10
a 5 (integer)
a = b b
b = a 10 (integer)
line 2 – bind b to 10
a = 5 List of variables Data/Objects stored in memory
b = 10
a 5 (integer)
a = b b
b = a 10 (integer)

EECS1015 – York University -- Prof. Michael S. Brown 62


Swap – Think like the interpreter (2/2)
line 2 – bind b to 10 (this is from the last slide)
a = 5 List of variables Data/Objects stored in memory
b = 10
a 5 (integer)
a = b b
b = a 10 (integer)

line 3 – bind a to the same object that b is bound to.


a = 5 List of variables Data/Objects stored in memory
b = 10
a 5 (integer)
a = b b
b = a 10 (integer)

line 4 – bind b to the same object that a is bound to.


a = 5 List of variables Data/Objects stored in memory
b = 10
a 5 (integer)
a = b b
b = a 10 (integer)
But for this line of code, a is already bound to the data that b is also bound
to. So this is like saying b=b. We have lost access to the "5"
EECS1015 – York University -- Prof. Michael S. Brown 63
Correct Swap
Python code
a = 5
b = 10
temp = a
a = b We have to introduce a new variable to
b = temp keep track of what a was bound to.
print(a)
print(b)

Python interpreter output


10
5
Now the results are correct.

Try it in trinket https://trinket.io/python/fc6809d587


Fix it yourself above.
EECS1015 – York University -- Prof. Michael S. Brown 64
Correct Swap – Interpreter (1/2)
Before program runs, Python interpreter already has this determined.
a = 5
List of variables Data/Objects stored in memory
b = 10
temp = a a 5 (integer)
a = b b
10 (integer)
b = temp temp
line 1 – bind variable a to 5
a = 5
b = 10 List of variables Data/Objects stored in memory
temp = a a 5 (integer)
a = b b
b = temp temp 10 (integer)

a = 5 line 2 – bind variable b to 10


b = 10 List of variables Data/Objects stored in memory
temp = a a
a = b 5 (integer)
b
b = temp temp 10 (integer)

EECS1015 – York University -- Prof. Michael S. Brown 65


Correct Swap – Interpreter (2/2)
line 3 – bind variable temp to the object that a is bound to (5)
a = 5
List of variables Data/Objects stored in memory
b = 10
temp = a a 5 (integer)
a = b b
10 (integer)
b = temp temp
line 4 – bind variable a to the object that b is bound to (10)
a = 5
b = 10 List of variables Data/Objects stored in memory Note. The code in line 4
temp = a a does not affect variable temp.
5 (integer)
a = b b
b = temp temp 10 (integer)

a = 5 line 5 – bind variable b to the object that temp is bound to (5)


b = 10 List of variables Data/Objects stored in memory
temp = a a
a = b 5 (integer)
b
b = temp temp 10 (integer)
Thanks to the temp variable, we had a way to keep a binding to the
value initial in "a". Now b is linked to 5.
EECS1015 – York University -- Prof. Michael S. Brown 66
Part 5: More on String variables

EECS1015 – York University -- Prof. Michael S. Brown 67


String
• Early, we said there were two common literals in Python: Numerical literals and
Strings
• Strings are written in quotations marks
• Strings are data that contain characters
• We call it a string this because it can be thought of characters tied together by a string
• We can count the number of characters in a string
• The counting starts at 0, not at 1. This is very important. This string has 11 characters.
• Notice that the space is considered a character
0 8 9 10
1 2 3 4 5 6 7 string

"Hello World"
EECS1015 – York University -- Prof. Michael S. Brown 68
String vs other literals
• Even though strings can look like other literals, we need to keep in
mind they are different

• For example:
"1234" is the sequence of characters "1", "2", "3", 4"
It is not the number 1234.

"None" is the sequence of characters "N", "o", "n", "e"


It is not the literal for None

EECS1015 – York University -- Prof. Michael S. Brown 69


String Math (Concatenation)
• We can "add" strings together
• This is called string concatenation
• Concatenation in English means to stick two things together
• We use the + operator to perform concatenation.
x = "Hello"
y = "World"
print(x + y)
print(x + " " + y)

HelloWorld
Hello World

EECS1015 – York University -- Prof. Michael S. Brown 70


String concatenation
• We can create a new string by merging two strings together

"String1" + "String2"

"String1String2"

• When the "+" is used with Strings, it is not the math add operator, but
the concatentation.

• Sometimes we say "concat" instead of concatenation

EECS1015 – York University -- Prof. Michael S. Brown 71


Multiple string concat expression
• We can add more than one string in a single expression
• This will be evaluated just like a math expression (x + y + z) – one step at a
time.
word1 = "EECS"
word2 = "1015"
Think like the interpreter

x = word1 + word2 + " is awesome"

step 1: Replace word1 with its value "EECS" + word2 + " is awesome"

step 2: Replace word2 with its value "EECS" + "1015" + " is awesome"

step 3: Concat to "EECS" and "1015" "EECS1015" + " is awesome"

step 4: Concat to "EECS1015" + "is awesome" "EECS1015 is awesome"

step 5: Assign x to the new string x = "EECS1015 is awesome"

EECS1015 – York University -- Prof. Michael S. Brown 72


String Example – Think like an interpreter (1/3)
The interpreter makes an initial scan of the program as has the following:
x = "Hello" List of variables Data/Objects stored in memory
x = x + " " "Hello" (string)
x
x = x + "World" "World" (string)
print(x) " " (string)

Line 1: Bind variable x to the string data "Hello"


x = "Hello" List of variables Data/Objects stored in memory
x = x + " "
x "Hello" (string)
x = x + "World"
print(x) "World" (string)
" " (string)

EECS1015 – York University -- Prof. Michael S. Brown 73


String Example – Think like an interpreter (2/3)
Line 2: Concat "Hello" and " ", create new string "Hello " and bind it to x.
x = "Hello" List of variables Data/Objects stored in memory
x = x + " "
x "Hello" (string)
x = x + "World"
print(x) "World" (string)
" " (string)
"Hello " (string)

Line 3: Concat "Hello " and "World", create new string "Hello World" and bind it to x.
x = "Hello" List of variables Data/Objects stored in memory
x = x + " "
x "Hello" (string)
x = x + "World"
print(x) "World" (string)
" " (string)
"Hello " (string)
"Hello World" (string)

EECS1015 – York University -- Prof. Michael S. Brown 74


String Example – Think like an interpreter (3/3)
Line 4: Call print function with data bound to x.
x = "Hello" List of variables Data/Objects stored in memory
x = x + " "
x "Hello" (string)
x = x + "World"
print(x) "World" (string)
" " (string)
"Hello " (string)
"Hello World" (string)

EECS1015 – York University -- Prof. Michael S. Brown 75


Match sure to match your "" correctly
• Another common mistake is to forget or have two many quotes
• See here

x = "EECS" Do you see it?


y = "is awesome" This can be hard to find?
z = x + "1015"" + y + "!"

EECS1015 – York University -- Prof. Michael S. Brown 76


Match sure to match your "" correctly
• Another common mistake is to forget or have two many "
• See here

x = "EECS" This will cause an Syntax error.


y = "is awesome"
z = x + "1015"" + y + "!" Note that your Pycharm IDE will help you.
In this case it draws a red line underneath the code
indicating something is not right.

EECS1015 – York University -- Prof. Michael S. Brown 77


The empty string! ""
• For integers and floats, we can have the value of 0
• This means "nothing"
• Is there something similar for a string?
• Yes
• The empty string, it is a string with no characters

x = ""
Python knows that stuff between
"" is a string. In this case, there is
nothing there. That is fine, this is
still a valid string.

We call this the empty string, or null string.


In computer science we like to call things
EECS1015 – York University -- Prof. Michael S. Brown without values "null". 78
Errors from mixing data types
Python code
x = "1234"
print( x ) Variable x type is a string.
y = 1234 Variable y type is an integer.
print( y ) Here we try to add a string
z = x + y and an integer.
print( z )

Python interpreter output We get a run-time "TypeError" that tells use we


1234 cannot concatenate a str and an integer.
1234
z = x + y
TypeError: can only concatenate str (not "int") to str

Try it in trinket https://trinket.io/python/55086aca3e

EECS1015 – York University -- Prof. Michael S. Brown 79


Part 6: Getting input from the user

EECS1015 – York University -- Prof. Michael S. Brown 80


Getting data from the user
• We can use the input function to get input from the user.

• The format of the function:

variable = input("string prompt")

The result will be the string the The string here is optional. We call this
user types in. the "prompt".

EECS1015 – York University -- Prof. Michael S. Brown 81


Input function example 1
Python code
x = input("Enter first number: ")
y = input("Enter second number: ")
z = x + y Remember, the result of the input function
print(z) is a string. What will the + operator do?

Python interpreter input/output


Enter first number: 10 If the user inputs 10, then 20, the answer is
Enter second number: 20 not 30, but 1020. Why?
1020 The input are strings, not numbers.

Try it in trinket https://trinket.io/python/1d9f865306

EECS1015 – York University -- Prof. Michael S. Brown 82


Trinket IO and input
Step 1: Click "run"
I've already clicked it, the "run" has Step 2: Click in "Result" window to change
change to a "stop" icon. focus to this window so you can type in the input.
Otherwise it will type in on the code window..

EECS1015 – York University -- Prof. Michael S. Brown 83


Input function example 2
Python code
prompt = "Enter a number: "
x = input(prompt) The input function takes a string as the
y = input(prompt) prompt. This string can be from a variable.
z = input()
w = x + y + z Also, you can use input without a prompt.
print(w)

Python interpreter input/output


Enter a number: 10.9
Enter a number: 20.8 Input for the empty input() statement.
1.11 Again, the results is from string concat,
10.920.81.11 not from addition.

EECS1015 – York University -- Prof. Michael S. Brown 84


Converting strings to numbers: int(), float()
• We can concert strings to integers or floats using the following
functions:
int( "string" )
float( "string")

x = "1234" x = "10.5"
y = int("1234") y = float("10.5")
print(x) print(x)
print(y) print(y)
print(type(x)) print(type(x))
print(type(y)) print(type(y))

1234 10.5
1234 10.5
<class 'str'> <class 'str'>
<class 'int'> <class 'float'>
EECS1015 – York University -- Prof. Michael S. Brown https://trinket.io/python/ea18acd09f 85
Input with string to numerical conversion
Python code
prompt = "Enter a number: " Think like the interpreter:
x = input(prompt) w = int(x) + int(y)
Let's examine this statement
y = input(prompt)
w = int(x) + int(y)
step 1: Replace x with its value w = int("10") + int(y)
print(w)
step 2: call int("10") and return integer 10 w = 10 + int(y)

step 3: replace y with its value w = 10 + int("20")

step 4: call int("20") and return integer 20 w = 10 + 20


Python interpreter input/output
Enter a number: 10 step 5: evaluate 10+20 to get value 30 w = 30
Enter a number: 20
30 step 6: bind variable w to value 30 w = 30

https://trinket.io/python/ab318de516 Question: What are the values of x and y after the print(w).
Are they strings or integers?

EECS1015 – York University -- Prof. Michael S. Brown 86


What if the string is not a number?
x = int("1234") OK . . result will be integer 1234

y = int(" 20") OK . . result will be integer 20. Python will ignore the spaces.

z = int("hello") Error – this will case a run-time error.

w = int("1234x") Error – this will case a run-time error.

u = int("1.2") Error – this will case a run-time error. 1.2 is not an integer.

x = float("1234") OK . . result will be float 1234.0

y = float(" 20.0 ") OK . . result will be floate 20.0. Python will ignore the spaces.

z = float("hello") Error – this will case a run-time error.

w = float("12.334x") Error – this will case a run-time error.

u = float("00034.2") OK . . result will be float 34.2, leading 0 are ignored.


EECS1015 – York University -- Prof. Michael S. Brown 87
Nested functions
• In the previous example, after we called input(), we passed the result
to int(). We can combine these functions into a single expression.
Think like the interpreter:
prompt = "Enter a number: " Let's examine this statement x = int(input(prompt))
x = int(input(prompt))
y = int(input(prompt))
step 1: Replace prompt with its value x = int(input("Enter a number:")
w = x + y
print(w)
step 2: call input(). Let's assume the x = int("20")
user typed in 20 -- result is a string "20"

step 3: call input("20"). This returns x = 20


an integer 20.

https://trinket.io/python/56112d5323 step 4: bind variable x to value 20 x = 20

Question: What are the values of x and y after the print(w).


EECS1015 – York University -- Prof. Michael S. Brown
Are they strings or integers? 88
Nest functions
• In Python (and most programming languages) it is very common to
have a function call inside another function

Consider this nest functions:

print( int( input("Enter a number: " )))


1 Call the input() function

2 Call the int() function with the result from input(..)

3 Call the print() function with the result from int(..)

EECS1015 – York University -- Prof. Michael S. Brown 89


Part 7: Putting it all together

EECS1015 – York University -- Prof. Michael S. Brown 90


Your first program: Kilometers to Miles
Task: Write a program that asks the user for some distance in Kilometers and converts this to Miles.

Before we start the program, we can begin planning our program.


(1) We will need to know he formula to convert from km to miles! (Google/Baidu can help!)
(2) We need to call input()
(3) We will need a variable to hold the value the user provides
(4) we will need a variable to store our conversion after applying the conversion function
(5) We will need to call a print() function

Quick "google": km to miles


1km = 0.621371 miles

EECS1015 – York University -- Prof. Michael S. Brown 91


Input function example 2
Python code
kilometers = input("Enter a distance in km: ")
miles = kilometers * 0.621371
print("In miles:")
print(miles) Wow! This causes an error. What did we forget?
The program looks correct!

Python interpreter input/output


Enter a distance in km: 10.5

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

EECS1015 – York University -- Prof. Michael S. Brown 92


Kilometers to Miles
Task: Write a program that asks the user for some distance in Kilometers and converts this to Miles.

Before we start the program, we already know


(1) We will need to know he formula to convert from km to miles.
(2) We need to call input()
(3) We will need a variable to hold the value the user provides
(4) we will need a variable to store our conversion after applying the conversion function
(5) We will need to call a print() function

We have to remember that input returns


a string. Since we will apply math operators
Quick google: km to miles on our variable later, we need to do a conversion.
1km = 0.621371 miles
Let's do float, since the user may input either
a whole number or decimal number.

EECS1015 – York University -- Prof. Michael S. Brown 93


Kilometers to Miles
Task: Write a program that asks the user for some distance in Kilometers and converts this to Miles.

Before we start the program, we already know


(1) We will need to know he formula to convert from km to miles.
(2) We need to call input()
(3) We will need a variable to hold the value the user provides
(4) NEW – We will need to convert the string value to a float
(5) we will need a variable to store our conversion after applying the conversion function
(6) We will need to call a print() function

Quick google: km to miles


1km = 0.621371 miles

EECS1015 – York University -- Prof. Michael S. Brown 94


Input function example 2
Python code
kilometers = input("Enter a distance in km: ")
miles = float(kilometers) * 0.621371
print("In miles:")
print(miles) We have added float().

We could have done this many ways, what


are other ways to use float in the program?

Python interpreter input/output


Enter a distance in km: 42.2
In miles:
26.2218562

https://trinket.io/python/4fc9488ca4
Try fixing the code yourself here.
EECS1015 – York University -- Prof. Michael S. Brown 95
Finally comments - comments
• You have noticed in my trinket code I put in comments.
• In Python, we can add comments to the code using the # symbol
• Anything after # will be considered a comment
• Comments are used by programmers to describe their code
• It is important to get into the habit of using comments
# Program – KM to Miles
# Author: You
# For: EECS1015
## You can use more than one #
kilometers = input("Enter a distance in km: ")
miles = float(kilometers) * 0.621371 # you can also comment here.
print("In miles:")
print(miles)

EECS1015 – York University -- Prof. Michael S. Brown 96


Summary
• There was a lot of material for this topic
• Literals, variables, data types (integers, floats, strings),
expressions/statements, math operators, input, int(), float(), and various
errors

• You also learned to take the program and break it down step by step.
This allowed you to "think the interpreter"

• With this lecture you should be able to write your own simple
programs in Python

EECS1015 – York University -- Prof. Michael S. Brown 97

You might also like