0% found this document useful (0 votes)
33 views50 pages

W1 Pre Class

This document outlines the foundational concepts of Python programming, including literals, data types, operators, and function calls. It emphasizes the importance of understanding Python's storage model, operator precedence, and the distinction between expressions and values. Additionally, it provides examples and quizzes to reinforce learning about values, operators, and the use of functions in Python.

Uploaded by

deeto_88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views50 pages

W1 Pre Class

This document outlines the foundational concepts of Python programming, including literals, data types, operators, and function calls. It emphasizes the importance of understanding Python's storage model, operator precedence, and the distinction between expressions and values. Additionally, it provides examples and quizzes to reinforce learning about values, operators, and the use of functions in Python.

Uploaded by

deeto_88
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

W1 Pre-Class

Acknowledgement / license
This and other lessons used in this unit throughout the semester are based on the online book
Foundations of Python Programming hosted on Runestone Academy, licensed under MIT and CC-BY.
Each Student must agree to accept these Terms, including the License, prior to their use of the
Service.
Learning Outcomes
In this lesson we will explore several basic building blocks of Python programs:

literals, like numbers and character strings


operators, like + and *
function calls, which take values as inputs and compute new values
variables, which save values so they can be used later in the program

These are the basic building blocks that are assembled to create programs that you interact with
every day—from the software running on your smartwatch, to the infrastructure behind the largest
websites, and every app running on your phone.

By the end of this lesson you should be able:

To understand Python’s storage model


To understand operator precedence
To distinguish between expressions, values, and printed representations
To recognize & explain hard coding
1.1 Values and Data Types
A value is one of the fundamental things — like a word or a number — that a program manipulates.
Some values are 5 (the result when we add 2 + 3 ), and "Hello, World!" . These objects are
classified into different classes, or data types: 4 is an integer, and “Hello, World!” is a string, so-called
because it contains a string or sequence of letters. You (and the interpreter) can identify strings
because they are enclosed in quotation marks.

We can specify values directly in the programs we write. For example we can specify a number as a
literal just by (literally) typing it directly into the program (e.g., 5 or 4.32 ). In a program, we specify
a word, or more generally a string of characters, by enclosing the characters inside quotation marks
(e.g., "Hello, World!" ).

During execution of a program, the Python interpreter creates an internal representation of literals
that are specified in a program. It can then manipulate them, for example by multiplying two
numbers. We call the internal representations objects or just values.

You can’t directly see the internal representations of values. You can, however, use the print
function to see a printed representation in the output window.

The printed representation of a number uses the familiar decimal representation (reading Roman
Numerals is a fun challenge in museums, but thank goodness the Python interpreter doesn’t present
the number 2014 as MMXIV in the output window). Thus, the printed representation of a number
shown in the output window is the same as the literal that you specify in a program.

The printed representation of a character string, however, is not exactly the same as the literal used
to specify the string in a program. For the literal in a program, you enclose the string in quotation
marks. The printed representation, in the output window, omits the quotation marks.

print(3.2)
print("Hello, World!")

Note:
Literals appear in programs. The Python interpreter turns literals into values, which have internal
representations that people never get to see directly. Outputs are external representations of values that
appear in the output window. When we are being careful, we will use the terms this way. Sometimes, however,
we will get a little sloppy and refer to literals or external representations as values.

Numbers with a decimal point belong to a class called float, because these numbers are represented
in a format called floating-point. At this stage, you can treat the words class and type interchangeably.
We’ll come back to a deeper understanding of what a class is in later chapters.

You will soon encounter other types of objects as well, such as lists and dictionaries. Each of these
has its own special representation for specifying an object as a literal in a program, and for displaying
an object when you print it. For example, list contents are enclosed in square brackets [ ] . You will
also encounter some more complicated objects that do not have very nice printed representations:
printing those won’t be very useful.
1.2 Quiz

Question Submitted Mar 2nd 2025 at 2:50:01 pm

What appears in the output window when the following statement executes?

print("Hello, FIT9136 Students!")

Nothing; the output is sent to the printer.

"Hello, FIT9136 Students!"

'Hello, FIT9136 Students!'

Hello, FIT9136 Students!


1.3 Operators and Operands
You can build complex expressions out of simpler ones using operators. Operators are special
tokens that represent computations like addition, multiplication and division. The values the operator
works on are called operands.

The following are all legal Python expressions whose meaning is more or less clear:

20 + 32
5 ** 2
(5 + 9) * (15 - 7)

The tokens + , - , and * , and the use of parentheses for grouping, mean in Python what they mean
in mathematics. The asterisk ( * ) is the token for multiplication, and ** is the token for
exponentiation. Addition, subtraction, multiplication, and exponentiation all do what you expect.

Remember that if we want to see the results of the computation, the program needs to specify that
with the word print . The first three computations occur, but their results are not printed out.

20 + 32
5 ** 2
(5 + 9) * (15 - 7)
print(7 + 5)

In Python 3, which we will be using, the division operator / produces a floating point result (even if
the result is an integer; 4/2 is 2.0 ). If you want truncated division, which ignores the remainder, you
can use the // operator (for example, 5//2 is 2 ).

print(9 / 5)
print(5 / 9)
print(9 // 5)

Pay particular attention to the examples above. Note that 9//5 truncates rather than rounding, so it
produces the value 1 rather than 2.

The truncated division operator, // , also works on floating point numbers. It truncates to the nearest
integer, but still produces a floating point result. Thus 7.0 // 3.0 is 2.0 .

print(7.0 / 3.0)
print(7.0 // 3.0)

The modulus operator, sometimes also called the remainder operator or integer remainder
operator works on integers (and integer expressions) and yields the remainder when the first
operand is divided by the second. In Python, the modulus operator is a percent sign ( % ). The syntax
is the same as for other operators.
print(7 // 3) # This is the integer division operator
print(7 % 3) # This is the remainder or modulus operator

In the above example, 7 divided by 3 is 2 when we use integer division and there is a remainder of 1.

The modulus operator turns out to be surprisingly useful. For example, you can check whether one
number is divisible by another—if x % y is zero, then x is divisible by y . Also, you can extract the
right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in
base 10). Similarly x % 100 yields the last two digits.
1.4 Quiz

Question 1 Submitted Mar 2nd 2025 at 2:53:06 pm

What value is printed when the following statement executes?

print(18 / 4)

4.5

4.0

Question 2 Submitted Mar 2nd 2025 at 2:53:16 pm

What value is printed when the following statement executes?

print(-16 / 4)

-4.0

4.0

-4

Question 3 Submitted Mar 2nd 2025 at 2:53:42 pm

What value is printed when the following statement executes?

print(18.0 // 4)
4.5

4.0

Question 4 Submitted Mar 2nd 2025 at 2:54:31 pm

Which of these statements would print the answer 3?

print(10 / 3)

print(9 / 3)

print(7 % 4)

print(7.0 % 4)
1.5 Function Calls
The Python interpreter can compute new values with function calls. You are familiar with the idea of
functions from high school algebra. There you might define a function f by specifying how it
transforms an input into an output, f(x) = 3x + 2 . Then, you might write f(5) and expect to get
the value 17.

Python adopts a similar syntax for invoking functions. If there is a named function foo that takes a
single input, we can invoke foo on the value 5 by writing foo(5) .

There are many built-in functions available in Python. You’ll be seeing some in this chapter and the
next couple of chapters.

Functions are like factories that take in some material, do some operation, and then send out the
resulting object.

In this case, we refer to the materials as arguments or inputs and the resulting object is referred to as
output or return value. This process of taking input, doing something, and then sending back the
output is demonstrated in the gif below.
Note
Don’t confuse the “output value” of a function with the output window. The output of a function is a Python
value and we can never really see the internal representation of a value. But we can draw pictures to help us
imagine what values are, or we can print them to see an external representation in the output window.

To confuse things even more, print is actually a function. All functions produce output values. Only the
print function causes things to appear in the output window.

It is also possible for programmers to define new functions in their programs. You will learn how to
do that later in the course. For now, you just need to learn how to invoke, or call, a function, and
understand that the execution of the function returns a computed value.

def square(x):
return x * x

def sub(x, y):


return x - y

We’ve defined two functions above. You do not have to understand how the code works exactly
(yet), we'll cover this later in the unit. square takes a single input parameter, and returns that
input multiplied by itself. sub takes two input parameters and returns the result of subtracting the
second from the first. Obviously, these functions are not particularly useful, since we have the
operators * and - available. But they illustrate how functions work. The visual below illustrates how
the square function works.

def square(x): # As mentioned earlier you don't have to worry about how this works, just know that
return x * x
def sub(x, y): # As mentioned earlier you don't have to worry about how this works, just know that
return x - y

print(square(3))
square(5)
print(sub(6, 4))
print(sub(5, 9))

Notice that when a function takes more than one input parameter, the inputs are separated by a
comma. Also notice that the order of the inputs matters. The value before the comma is treated as
the first input, the value after it as the second input.

Again, remember that when Python performs computations, the results are only shown in the output
window if there’s a print statement that says to do that. In the activecode window above, square(5)
produces the value 25 but we never get to see that in the output window, because it is not printed.
1.5.1 Function calls as part of complex expressions
Anywhere in an expression that you can write a literal like a number, you can also write a function
invocation that produces a number.

def square(x): # As mentioned earlier you don't have to worry about how this works, just know that
return x * x

def sub(x, y): # As mentioned earlier you don't have to worry about how this works, just know that
return x - y

print(square(3) + 2)
print(sub(square(3), square(1+1)))

Let's follow through and see how the execution unfolds for print(sub(square(3), square(1+1))) .

Notice that we always have to resolve the expression inside the innermost parentheses first, in order
to determine what input to provide when calling the functions.

1. print(sub(square(3), square(1+1)))
2. print(sub(9, square(1+1)))
3. print(sub(9, square(2)))
4. print(sub(9, 4))
5. print(5)

Note:
The Python interpretor evaluates expressions starting from the left going towards the right while also
following order of operations (e.g. PEMDAS), with the exception of exponents where it evaluates right to left.
For example, if the expression to evaluate in Python is 2**(9%3+2)+12/(5.5-7.5) , then Python would
evaluate everything in brackets first resulting in 2**2+12/-2.0 , then the exponentiation resulting in
4+12/-2.0 , then the division resulting in 4+(-6.0) and finally the addition resulting in a result of -2.0.
1.5.2 Functions are objects; parentheses invoke functions
Remember that earlier we mentioned that some kinds of Python objects don’t have a nice printed
representation? Functions are themselves just objects. If you tell Python to print the function object,
rather than printing the results of invoking the function object, you’ll get one of those not-so-nice
printed representations.

Just typing the name of the function refers to the function as an object. Typing the name of the
function followed by parentheses () invokes the function.

def square(x): # As mentioned earlier you don't have to worry about how this works, just know that
return x * x

def sub(x, y): # As mentioned earlier you don't have to worry about how this works, just know that
return x - y

print(square) # This is the print() for the not-so-nice printed representations.


print(square(3))
1.6 Data Types
If you are not sure what class (data type) a value falls into, Python has a function called type which
can tell you.

print(type("Hello, World!"))
print(type(17))
print("Hello, World")
print(type(3.2))

What about values like "17" and "3.2" ? They look like numbers, but they are in quotation marks
like strings.

print(type("17"))
print(type("3.2"))

They’re strings!

Strings in Python can be enclosed in either single quotes ( ' ) or double quotes ( " ), or three of each
( ''' or """ ).

print(type('This is a string.'))
print(type("And so is this."))
print(type("""and this."""))
print(type('''and even this...'''))

Double quoted strings can contain single quotes inside them, as in "Bruce's beard" , and single
quoted strings can have double quotes inside them, as in 'The knights who say "Ni!"' . Strings
enclosed with three occurrences of either quote symbol are called triple quoted strings. They can
contain either single or double quotes:

print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')

Triple quoted strings can even span multiple lines:

print("""This message will span


several lines
of the text.""")

Python doesn’t care whether you use single or double quotes or the three-of-a-kind quotes to
surround your strings. Once it has parsed the text of your program or command, the way it stores
the value is identical in all cases, and the surrounding quotes are not part of the value.

print('This is a string.')
print("""And so is this.""")
So the Python language designers usually chose to surround their strings by single quotes. What do
you think would happen if the string already contained single quotes?

When you type a large integer, you might be tempted to use commas between groups of three digits,
as in 42,000 . This is not a legal integer in Python, but it does mean something else, which is legal:

print(42500)
print(42,500)

Well, that’s not what we expected at all! Because of the comma, Python chose to treat this as a pair of
values. In fact, a print statement can print any number of values as long as you separate them by
commas. Notice that the values are separated by spaces when they are displayed.

print(42, 17, 56, 34, 11, 4.35, 32)


print(3.4, "hello", 45)

Remember not to put commas or spaces in your integers, no matter how big they are. Also revisit
what we said in the previous chapter: formal languages are strict, the notation is concise, and even
the smallest change might mean something quite different from what you intended.
1.7 Quiz

Question 1 Submitted Mar 2nd 2025 at 3:07:45 pm

How can you determine the type of a variable?

Print out the value and determine the data type based on the value printed.

Use the type function.

Use it in a known equation and print the result.

Look at the declaration of the variable.

Question 2 Submitted Mar 2nd 2025 at 3:07:54 pm

What is the data type of 'this is what kind of data'?

Character

Integer

Float

String
1.8 Type conversion functions
Sometimes it is necessary to convert values from one type to another. Python provides a few simple
function that will allow us to do that. The functions int , float and str will (attempt to) convert
their arguments into types int , float and str respectively. We call these type conversion
functions.

The int function can take a floating point number or a string, and turn it into an int. For floating
point numbers, it discards the decimal portion of the number — a process we call truncation towards
zero on the number line. Let us see this in action:

print(3.14, int(3.14))
print(3.9999, int(3.9999)) # This doesn't round to the closest int!
print(3.0, int(3.0))
print(-3.999, int(-3.999)) # Note that the result is closer to zero

print("2345", int("2345")) # parse a string to produce an int


print(17, int(17)) # int even works on integers
print(int("23bottles"))

The last case shows that a string has to be a syntactically legal number, otherwise you’ll get one of
those pesky runtime errors. Modify the example by deleting the bottles and rerun the program.
You should see the integer 23 .

The type converter float can turn an integer, a float, or a syntactically legal string into a float.

print(float("123.45"))
print(type(float("123.45")))

The type converter str turns its argument into a string. Remember that when we print a string, the
quotes are removed in the output window. However, if we print the type, we can see that it is
definitely str .

print(str(17))
print(str(123.45))
print(type(str(123.45)))

One common operation where you might need to do a type conversion is when you are
concatenating several strings together but want to include a numeric value as part of the final string.
Because we can’t concatenate a string with an integer or floating point number, we will often have to
convert numbers to strings before concatenating them.
1.9 Quiz

Question Submitted Mar 2nd 2025 at 3:14:39 pm

What value is printed when the following statement executes?

print(int(53.785))

Nothing is printed. It generates a runtime error.

53

54

53.785
1.10 Variables

An error occurred.

Try watching this video on www.youtube.com, or enable JavaScript if it is


disabled in your browser.

Source: [AC101 Youtube]

One of the most powerful features of a programming language is the ability to manipulate variables.
A variable is a name that refers to a value.

Assignment statements create new variables and also give them values to refer to.

message = "What's up, Doc?"


n = 17
pi = 3.14159

This example makes three assignments. The first assigns the string value "What's up, Doc?" to a
new variable named message . The second assigns the integer 17 to n , and the third assigns the
floating-point number 3.14159 to a variable called pi .

The assignment token, = , should not be confused with equality (we will see later that equality uses
the == token). The assignment statement links a name, on the left hand side of the operator, with a
value, on the right hand side. This is why you will get an error if you enter:

17 = n

Tip
When reading or writing code, say to yourself “n is assigned 17” or “n gets the value 17” or “n is a reference to
the object 17” or “n refers to the object 17”. Don’t say “n equals 17”.

A common way to represent variables on paper is to write the name with an arrow pointing to the
variable’s value. This kind of figure, known as a reference diagram, is often called a state
snapshot because it shows what state each of the variables is in at a particular instant in time. (Think
of it as the variable’s state of mind). This diagram shows the result of executing the assignment
statements shown above.

If your program includes a variable in any expression, whenever that expression is executed it will
produce the value that is linked to the variable at the time of execution. In other words, evaluating a
variable looks up its value.

message = "What's up, Doc?"


n = 17
pi = 3.14159

print(message)
print(n)
print(pi)

In each case the result is the value of the variable. To see this in even more detail, we can run the
program using Python Tutor (embedded below). Click "Next >" to see each step.
A great deal of programming is about having the computer remember things. For example, we might
want to keep track of the number of missed calls on your phone. Each time another call is missed, we
will arrange to update or change the variable so that it will always reflect the correct value.

Any place in a Python program where a number or string is expected, you can put a variable name
instead. The python interpreter will substitute the value for the variable name.

For example, we can find out the data type of the current value of a variable by putting the variable
name inside the parentheses following the function name type .

message = "What's up, Doc?"


n = 17
pi = 3.14159

print(type(message))
print(type(n))
print(type(pi))

Note
If you have programmed in another language such as Java or C++, you may be used to the idea that variables
have types that are declared when the variable name is first introduced in a program. Python doesn’t do that.
Variables don’t have types in Python; values do. That means that it is acceptable in Python to have a variable
name refer to an integer and later have the same variable name refer to a string. This is almost never a good
idea, because it will confuse human readers (including you), but the Python interpreter will not complain.
1.11 Quiz

Question Submitted Mar 2nd 2025 at 3:28:05 pm

What is printed when the following statements execute?

day = "Thursday"
day = 32.5
day = 19
print(day)

Nothing is printed. A runtime error occurs.

Thursday

"Thursday"

32.5

19

"19"
1.12 Variable Names and Keywords
Variable names can be arbitrarily long. They can contain both letters and digits, but they have to
begin with a letter or an underscore. Although it is legal to use uppercase letters, by convention we
don’t. If you do, remember that case matters. Bruce and bruce are different variables.

Caution
Variable names never contains spaces.

The underscore character ( _ ) can also appear in a name. It is often used in names with multiple
words, such as my_name or price_of_tea_in_china . There are some situations in which names
beginning with an underscore have special meaning, so a safe rule for beginners is to start all names
with a letter.

If you give a variable an illegal name, you get a syntax error. In the example below, each of the
variable names is illegal.

76trombones = "big parade"


more$ = 1000000
class = "Computer Science 101"

76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains an
illegal character, the dollar sign. But what’s wrong with class ?

It turns out that class is one of the Python keywords. Keywords define the language’s syntax rules
and structure, and they cannot be used as variable names. Python has thirty-something keywords
(and every now and again improvements to Python introduce or eliminate one or two):

You might want to keep this list handy. If the interpreter complains about one of your variable names
and you don’t know why, see if it is on this list.
1.13 Quiz

Question Submitted Mar 2nd 2025 at 3:29:41 pm

The following is a legal variable name in Python: A_good_grade_is_A+

True

False
1.14 Choosing the Right Variable Name
Programmers generally choose names for their variables that are meaningful to the human readers
of the program — they help the programmer document, or remember, what the variable is used for.
Beginning programmers sometimes think it is funny to use strange or obscene names for their
variables. This is not good practice and will not amuse your professor. Get in the habit of using
meaningful names right away.

Caution
Beginners sometimes confuse “meaningful to the human readers” with “meaningful to the computer”. So
they’ll wrongly think that because they’ve called some variable average or pi , it will somehow automagically
calculate an average, or automagically associate the variable pi with the value 3.14159. No! The computer
doesn’t attach semantic meaning to your variable names.

So you’ll find some instructors who deliberately don’t choose meaningful names when they teach beginners
— not because they don’t think it is a good habit, but because they’re trying to reinforce the message that
you, the programmer, have to write some program code to calculate the average, or you must write an
assignment statement to give a variable the value you want it to have.
1.15 Statements and Expressions
A statement is an instruction that the Python interpreter can execute. You have only seen the
assignment statement so far. Some other kinds of statements that you’ll see in future chapters are
while statements, for statements, if statements, and import statements. (There are other kinds
too!)

An expression is a combination of literals, variable names, operators, and calls to functions.


Expressions need to be evaluated. The result of evaluating an expression is a value or object.

If you ask Python to print an expression, the interpreter evaluates the expression and displays the
result.

print(1 + 1 + (2 * 3))
print(len("hello"))

In this example len is a built-in Python function that returns the number of characters in a string.

The evaluation of an expression produces a value, which is why expressions can appear on the right
hand side of assignment statements. A literal all by itself is a simple expression, and so is a variable.

y = 3.14
x = len("hello")
print(x)
print(y)

In a program, anywhere that a literal value (a string or a number) is acceptable, a more complicated
expression is also acceptable. Here are all the kinds of expressions we’ve seen so far:

literal
e.g., “Hello” or 3.14

variable name
e.g., x or len

operator expression
<expression> operator-name <expression>

function call expression


<expression>(<expressions separated by commas>)

Notice that operator expressions (like + and * ) have sub-expressions before and after the operator.
Each of these can themselves be simple or complex expressions. In that way, you can build up to
having pretty complicated expressions.

print(2 * len("hello") + len("goodbye"))

Similarly, when calling a function, instead of putting a literal inside the parentheses, a complex
expression can be placed inside the parentheses.

def square(x):
return x * x

def sub(x, y):


return x - y

x = 2
y = 1
print(square(y + 3))
print(square(y + square(x)))
print(sub(square(y), square(x)))

With a function call, it’s even possible to have a complex expression before the left parenthesis, as
long as that expression evaluates to a function object. For now, though, we will just use variable
names (like square, sub, and len) that are directly bound to function objects.

It is important to start learning to read code that contains complex expressions. The Python
interpreter examines any line of code and parses it into components. For example, if it sees an =
symbol, it will try to treat the whole line as an assignment statement. It will expect to see a valid
variable name to the left of the =, and will parse everything to the right of the = as an expression. It
will try to figure out whether the right side is a literal, a variable name, an operator expression, or a
function call expression. If it’s an operator expression, it will further try to parse the sub-expressions
before and after the operator. And so on. You should learn to parse lines of code in the same way.

In order to evaluate an operator expression, the Python interpreter first completely evaluates the
expression before the operator, then the one after, then combines the two resulting values using the
operator. In order to evaluate a function call expression, the interpreter evaluates the expression
before the parentheses (i.e., it looks up the name of the function). Then it tries to evaluate each of the
expressions inside the parentheses. There may be more than one, separated by commas. The values
of those expressions are passed as inputs to the function when the function is called.

If a function call expression is a sub-expression of some more complicated expression, as square(x)


is in sub(square(y), square(x)) , then the return value from square(x) is passed as an input to
the sub function. This is one of the tricky things that you will have to get used to working out when
you read (or write) code. In this example, the square function is called (twice) before the sub
function is called, even though the sub function comes first when reading the code from left to right.
In the following example we will use the notation of -add- to indicate that Python has looked up the
name add and determined that it is a function object.

x = 5
y = 7
add(square(y), square(x))

# Step by step output after invoking add(square(y), square(x))


1. add(square(y), square(x))
2. -add-(square(y), square(x))
3. -add-(-square-(y), square(x))
4. -add-(-square-(7), square(x))
5. -add-(49, square(x))
6. -add-(49, -square-(x))
7. -add-(49, -square-(5))
8. -add-(49, 25)
9. 74

To start giving you some practice in reading and understanding complicated expressions, try doing
the Parsons problem in the next slide.
1.16 Quiz

Question 1 Submitted Mar 2nd 2025 at 3:51:02 pm

Please order (drag and drop) the code fragments in the order in which the Python interpreter would
evaluate them. x is 2 and y is 3. Now the interpreter is executing square(x + y) .

look up the variable square to get the function object

look up the variable x to get 2

look up the variable y to get 3

add 2+3 to get 5

run the square function on input 5, returning the value 25

Question 2 Submitted Mar 2nd 2025 at 3:58:41 pm

Please order the code fragments in the order in which the Python interpreter would evaluate them. x
is 2 and y is 3. Now the interpreter is executing square(x + sub(square(y), 2 * x)) .
look up the variable square to get the function object

look up the variable x to get 2

look up the variable sub to get the function object

look up the variable square, again, to get the function object

look up the variable y to get 3

run the square function on input 3, returning the value 9

look up the variable x, again, to get 2

multiply 2*2 to get 4

run the sub function, passing inputs 9 and 4, returning the value 5

add 2 and 5 to get 7

run the square function, again, on input 7, returning the value 49


1.17 Order of Operations
When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence. Python follows the same precedence rules for its mathematical operators that
mathematics does.

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.
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?
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.
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.

Note
Due to some historical quirk, an exception to the left-to-right left-associative rule is the exponentiation
operator ** . A useful hint is to always use parentheses to force exactly the order you want when
exponentiation is involved:

print(2 ** 3 ** 2) # the right-most ** operator gets done first!


print((2 ** 3) ** 2) # use parentheses to force the order you want! and for readability purposes.

Note
This is a second way that parentheses are used in Python. The first way you’ve already seen is that () indicates
a function call, with the inputs going inside the parentheses. How can Python tell when parentheses specify to
call a function, and when they are just forcing the order of operations for ambiguous operator expressions?

The answer is that if there’s a an expression to the left of the parentheses that evaluates to a function object,
then the parentheses indicate a function call, and otherwise not. You will have to get used to making the same
inference when you see parentheses: is this a function call, or just specifying precedence?
1.18 Quiz

Question Submitted Mar 2nd 2025 at 4:01:48 pm

What is the value of the following expression:

16 - 2 * 5 // 3 + 1

14

24

13.667
1.19 Reassignment
As we have mentioned previously, it is legal to make more than one assignment to the same variable.
A new assignment makes an existing variable refer to a new value (and stop referring to the old
value).

bruce = 5
print(bruce)
bruce = 7
print(bruce)

The first time bruce is printed, its value is 5, and the second time, its value is 7. The assignment
statement changes the value (the object) that bruce refers to.

Here is what reassignment looks like in a reference diagram:

It is important to note that in mathematics, a statement of equality is always true. If a is equal to


b now, then a will always equal to b . In Python, an assignment statement can make two
variables refer to the same object and therefore have the same value. They appear to be equal.
However, because of the possibility of reassignment, they don’t have to stay that way:

a = 5
b = a # after executing this line, a and b are now equal
print(a,b)
a = 3 # after executing this line, a and b are no longer equal
print(a,b)

Line 4 changes the value of a but does not change the value of b , so they are no longer equal. We
will have much more to say about equality later in this unit.

Developing your mental model of How Python


Evaluates
Its important to start to develop a good mental model of the steps the Python interpreter takes when
evaluating an assignment statement. In an assignment statement, the interpreter first evaluates the
code on the right hand side of the assignment operator. It then gives a name to whatever that is. The
(very short) visualization below shows what is happening.

a = 5
b = a

In the first statement a = 5 the literal number 5 evaluates to 5, and is given the name a . In the
second statement, the variable a evaluates to 5 and so 5 now ends up with a second name b .

You can step through the code and see how the variable assignments change with Python Tutor.

Note
In some programming languages, a different symbol is used for assignment, such as <- or := . The intent is
that this will help to avoid confusion. Python chose to use the tokens = for assignment, and == for equality.
This is a popular choice also found in languages like C, C++, Java, and C#.
1.20 Quiz

Question Submitted Mar 2nd 2025 at 4:03:36 pm

After the following statements, what are the values of x and y?

x = 15
y = x
x = 22

x is 15 and y is 15

x is 22 and y is 22

x is 15 and y is 22

x is 22 and y is 15
1.21 Updating Variables
One of the most common forms of reassignment is an update where the new value of the variable
depends on the old. For example,

x = x + 1

This means get the current value of x, add one, and then update x with the new value. The new value
of x is the old value of x plus 1. Although this assignment statement may look a bit strange,
remember that executing assignment is a two-step process. First, evaluate the right-hand side
expression. Second, let the variable name on the left-hand side refer to this new resulting object. The
fact that x appears on both sides does not matter. The semantics of the assignment statement
makes sure that there is no confusion as to the result. For example:

x = 6
x = x + 1

1. x = x + 1
2. x = 6 + 1 # You can see that 'x' has been evaluated
3. x = 7 # Now the evaluation of the expression '6 + 1' has happened

x = 6 # initialize x
print(x)
x = x + 1 # update x
print(x)

If you try to update a variable that doesn’t exist, you get an error because Python evaluates the
expression on the right side of the assignment operator before it assigns the resulting value to the
name on the left. Before you can update a variable, you have to initialize it, usually with a simple
assignment. In the above example, x was initialized to 6.

Updating a variable by adding something to it is called an increment; subtracting is called a


decrement. Sometimes programmers talk about incrementing or decrementing without specifying
by how much; when they do they usually mean by 1. Sometimes programmers also talk about
bumping a variable, which means the same as incrementing it by 1.

Incrementing and decrementing are such common operations that programming languages often
include special syntax for it. In Python += is used for incrementing, and -= for decrementing. In
some other languages, there is even a special syntax ++ and -- for incrementing or decrementing
by 1. Python does not have such a special syntax. To increment x by 1 you have to write x += 1 or x
= x + 1.

Please note that the += operator has different meanings outside of integers. You will learn about this later.
x = 6 # initialize x
print(x)
x += 3 # increment x by 3; same as x = x + 3
print(x)
x -= 1 # decrement x by 1
print(x)

Imagine that we wanted to not increment by one each time but instead add together the numbers
one through ten, but only one at a time.

s = 1
print(s)
s = s + 2
print(s)
s = s + 3
print(s)
s = s + 4
print(s)
s = s + 5
print(s)
s = s + 6
print(s)
s = s + 7
print(s)
s = s + 8
print(s)
s = s + 9
print(s)
s = s + 10
print(s)

After the initial statement, where we assign s to 1, we can add the current value of s and the next
number that we want to add (2 all the way up to 10) and then finally reassign that that value to s so
that the variable is updated after each line in the code.

This will be tedious when we have many things to add together. Later you’ll read about an easier way
to do this kind of task.
1.22 Quiz

Question 1 Submitted Mar 2nd 2025 at 4:05:13 pm

What is printed when the following statements execute?

x = 12
x = x - 1
print(x)

12

-1

11

Nothing. An error occurs because x can never be equal to x - 1.

Question 2 Submitted Mar 2nd 2025 at 4:05:22 pm

What is printed when the following statements execute?

x = 12
x = x - 3
x = x + 5
x = x + 1
print(x)

12

15

Nothing. An error occurs because x cannot be used that many times in assignment
statements.
Question 3 Submitted Mar 2nd 2025 at 4:06:25 pm

Re-order the code (top being the statement that evaluates first and the bottom being the statement
that evaluates last) that will result in the value 134 being printed.

my_bank_balance = 100

my_bank_balance = my_bank_balance + 34

print(my_bank_balance)

Question 4 Submitted Mar 2nd 2025 at 4:06:57 pm

Which of the following statements are equivalent?

x=x+y

y += x

x += x + y

x += y

x++ y
1.23 Hard-Coding
As you begin programming, you’ll see that there are many ways to solve problems. You’ll also find
that one of the thrills of programming is how easily you can do things correctly that humans could
easily make errors on. For example, you’ll learn how to write just a very small bit of code to find the
1047th character in a sentence that might be thousands of letters long, and you’ll learn how to do the
exact same computation on many different pieces of data.

We’ll often tell you in this textbook not to hard-code answers. What does that mean?

Some things in programming you can only do by typing them out. As you’ve seen, when you have to
assign a value to a variable, you simply type something like xyz = 6 . No other way.

But in most cases, it’s best not to do computation in your head or write complete answers to
programming problems out by hand. That’s where hard-coding comes in. “Don’t hard code” basically
means, you should rely on your code, your logic, your program, and you should not write things out
by hand or do computation in your head – even if you can do so easily.

When you are writing code or working on the answer to a programming exericse, you should ask
yourself: Would my answer be correct even if the provided variables had different values? If the answer
to that question is no, you’re probably hard-coding, which you should avoid – and there’s probably at
least a slightly more concise way to construct your answer!

For example, in this following code, if you’re asked in an exercise to create a variable zx and assign it
the value of the sum of the value of y and the value of x , writing zx = 55 is hard-coding.

# Assume the variables y and x have already been initialised

zx = 55 # THIS IS HARD-CODING
zx = 20 + 35 # THIS IS ALSO HARD-CODING
zx = x + y # This is not hard-coding, you're letting the logic of the program do the work for you

The operation 20 + 35 may be easy math to do in your head or with a calculator, but when you
learn to program, you want to train yourself to notice useful patterns of how to solve problems,
which will make your life easier (perhaps beyond programming, even).

The correct way to answer that sort of exercise would be to write: zx = y + x (or zx = x + y , as
you were just reminded of the order of operations). That is not hard-coding, and it will be correct no
matter what the values of x and y are.

In the code above, if the value of x were 40 , 55 would not be the correct value for zx to have. But
zx = y + x would still be absolutely correct.

Try as much as you can not to rely on your brilliant but fallible human brain to do computation when
you program – use your brain to determine how to write the correct code to solve the problem for
you! That’s why we require you to avoid hard-coding for most exercises in this unit.
1.24 Input
Our programs get more interesting if they don’t do exactly the same thing every time they run. One
way to make them more interesting is to get input from the user. Luckily, in Python there is a built-in
function to accomplish this task. It is called input .

n = input("Please enter your name: ")

The input function allows the programmer to provide a prompt string. In the example above, it is
“Please enter your name: “. When the function is evaluated, the prompt is shown (in the browser, look
for a popup window). The user of the program can type some text and press return . When this
happens the text that has been entered is returned from the input function, and in this case
assigned to the variable n . Run this example a few times and try some different names in the input
box that appears.

n = input("Please enter your name: ")


print("Hello", n)

It is very important to note that the input function returns a string value. Even if you asked the user
to enter their age, you would get back a string like "17" . It would be your job, as the programmer, to
convert that string into an int or a float, using the int or float converter functions we saw earlier.

Note
We often use the word “input” (or, synonymously, argument) to refer to the values that are passed to any
function. Do not confuse that with the input function, which asks the user of a program to type in a value.
Like any function, input itself takes an input argument and produces an output. The input is a character
string that is displayed as a prompt to the user. The output is whatever character string the user types.

This is analogous to the potential confusion of function “outputs” with the contents of the output window.
Every function produces an output, which is a Python value. Only the print function puts things in the output
window. Most functions take inputs, which are Python values. Only the input function invites users to type
something.

Here is a program that turns a number of seconds into more human readable counts of hours,
minutes, and seconds. A call to input() allows the user to enter the number of seconds. Then we
convert that string to an integer. From there we use the division and modulus operators to compute
the results.

str_seconds = input("Please enter the number of seconds you wish to convert: ")
total_secs = int(str_seconds)

hours = total_secs // 3600


secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60

print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining)

The variable str_seconds will refer to the string that is entered by the user. As we said above, even
though this string may be 7684 , it is still a string and not a number. To convert it to an integer, we
use the int function. The result is referred to by total_secs . Now, each time you run the program,
you can enter a new value for the number of seconds to be converted.
1.25 Glossary
assignment statement
A statement that assigns a value to a name (variable). To the left of the assignment operator, = , is a
name. To the right of the assignment token is an expression which is evaluated by the Python
interpreter and then assigned to the name. The difference between the left and right hand sides of the
assignment statement is often confusing to new programmers. In the following assignment:

n = n + 1

n plays a very different role on each side of the = . On the right it is a value and makes up part of the
expression which will be evaluated by the Python interpreter before assigning it to the name on the
left.

assignment token
= is Python’s assignment token, which should not be confused with the mathematical comparison
operator signifying equality.

boolean expression
An expression that is either true or false.

boolean value
There are exactly two boolean values: True and False . Boolean values result when a boolean
expression is evaluated by the Python interepreter. They have type bool .

class
see data type below

comment
Information in a program that is meant for other programmers (or anyone reading the source code)
and has no effect on the execution of the program.

data type
A set of values. The type of a value determines how it can be used in expressions. So far, the types
you have seen are integers ( int ), floating-point numbers ( float ), and strings ( str ).

decrement
Decrease by 1.

evaluate
To simplify an expression by performing the operations in order to yield a single value.

expression
A combination of operators and operands (variables and values) that represents a single result value.
Expressions are evaluated to give that result.

float
A Python data type which stores floating-point numbers. Floating-point numbers are stored internally
in two parts: a base and an exponent. When printed in the standard format, they look like decimal
numbers. Beware of rounding errors when you use float s, and remember that they are only
approximate values.

increment
Both as a noun and as a verb, increment means to increase by 1.

initialization (of a variable)


To initialize a variable is to give it an initial value. Since in Python variables don’t exist until they are
assigned values, they are initialized when they are created. In other programming languages this is
not the case, and variables can be created without being initialized, in which case they have either
default or garbage values.

int
A Python data type that holds whole numbers.

integer division
An operation that divides one integer by another and yields an integer. Integer division yields only the
whole number of times that the numerator is divisible by the denominator and discards any
remainder.

keyword
A reserved word that is used by the compiler to parse program; you cannot use keywords like if ,
def , and while as variable names.

literal
A number or string that is written directly in a program. Sometimes these are also referred to as
literal values, or just values, but be careful not to confuse a literal value as written in a program with
an internal value maintained by the Python interpreter during execution of a program.

logical operator
One of the operators that combines boolean expressions: and , or , and not .

modulus operator
An operator, denoted with a percent sign ( % ), that works on integers and yields the remainder when
one number is divided by another.

object
Also known as a data object (or data value). The fundamental things that programs are designed to
manipulate (or that programmers ask to do things for them).

operand
One of the values on which an operator operates.
operator
A special symbol that represents a simple computation like addition, multiplication, or string
concatenation.

prompt string
Used during interactive input to provide the use with hints as to what type of value to enter.

reference diagram
A picture showing a variable with an arrow pointing to the value (object) that the variable refers to.
See also state snapshot.

rules of precedence
The set of rules governing the order in which expressions involving multiple operators and operands
are evaluated.

state snapshot
A graphical representation of a set of variables and the values to which they refer, taken at a
particular instant during the program’s execution.

statement
An instruction that the Python interpreter can execute. So far we have only seen the assignment
statement, but we will soon meet the import statement and the for statement.

str
A Python data type that holds a string of characters.

type conversion function


A function that can convert a data value from one type to another.

value
A number or string (or other things to be named later) that can be stored in a variable or computed in
an expression.

variable
A name that refers to a value.

variable name
A name given to a variable. Variable names in Python consist of a sequence of letters (a..z, A..Z, or _)
and digits (0..9) that begins with a letter. In best programming practice, variable names should be
chosen so that they describe their use in the program, making the program self documenting.
Feedback
Please provide feedback on this lesson.

Question 1 Submitted Mar 2nd 2025 at 4:10:49 pm

This lesson took me...

Less than 60 minutes

Between 60 and 90 minutes

Between 90 and 120 minutes

More than 120 minutes

Question 2 Submitted Mar 2nd 2025 at 4:11:13 pm

What worked best for you?

Practical learning help me understand the context & theory

Question 3 Submitted Mar 2nd 2025 at 4:12:19 pm

What would you want us to improve? (Including typos, bugs, resources)

Let student write down their own code, instead just read & drag-drop

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy