CMPT120 J.
Ye
Variables
&
Control Structures (1)
• Variables
• Arithmetic
• Conditional statements
• User Input
1
Python Comments
• In Python, comments are lines that start with a #
• Comments let you include information that is meant only
for the programmer. The Python interpreter ignores
comments.
• Comments make code easier to understand, thus easier to
maintain
• Useful tip: if you need to comment out a Python code
block, select the block, use two keys alt+3; to reverse it,
use alt+4
3
Variables
What is a variable?
• Variables hold “values” that may vary
• In computer programming, a variable is the name of a
memory address (location) that can store a value or a
piece of information.
• Python variables do not directly store values, but store
references to(addresses of) the actual value – this will be
discussed in more detail later.
• Whenever we need the program to temporarily
remember some information, we will use a variable to
hold it
3
Variables
Types of Variables
• A variable holds a specific type of information (or value)
• Some common types we are going to use are:
– boolean A boolean value can be either True or False
– integer such as 923, -5
– float Any rational number, such as 2.678
– string Any sequence of characters, such as “cmpt120”
• Note: string “12” and integer 12 are completely different
entities. We can use function type(x) to check the type of x
• Variable Type in Python (and many other languages) is an
important issue
4
Variables
Variable Assignment
• To assign a value to a variable, we use a variable assignment
statement, for example, all the three instructions as follows are
variable assignment statements:
age = 20
n1 = 10.5
n = n1 + 5
age, n1, and n are all variables. They got the value 20, 10.5,
and 15.5 respectively after these instructions
• Once a variable (e.g. n1) got a value (10.5), whenever we want
to use the value, we can use the variable name to represent the
value
5
Variables
Examples
aString = "123" # aString is a variable
print(aString) # we're invoking function print
aString = "456" # now aString holds a new value
aString = aString + "789"
# if a and b are two strings, a+b combines
# two strings into one
print(aString) # output?
6
Variable Names Variables
• Consist of letters, digits and/or underscore, no other characters
• Case matters
e.g. sum and Sum are two different variables
• Begin with a letter, not a digit
• Python reserved words/keywords cannot be variables
To check the keyword list, type following commands in interpreter:
>>> import keyword
>>> keyword.kwlist
• Should be meaningful, thus can be long
e.g. average_salary, numOfChars, person3
• By convention, begin with a lower-case letter
• Don’t use function name as a variable
7
Arithmetic
Arithmetic Operators
Higher Precedence
() brackets
** exponentiation (ab : a**b)
+, − unary plus / minus
*, / , % , // multiplication, division, modulo, floor division
+, − (binary) addition, subtraction
Lower Precedence
E.g. 2 ** (6 / 2) + − 4 − 5 % 3 evaluates to 2.0
8
Arithmetic
Beyond Basic Arithmetic
• You can find more mathematic functions in the math
module
– A module is a file containing functions and variables that can be
imported to another program
– From Python shell, go to help -> Python docs -> global module
index, you can see various pre-defined modules
• E.g.
>>> import math
>>> math.sqrt (9)
3.0
>>> math.factorial (5)
120
>>> math.pi
3.1415926535897931 9
User Input
• A program can take user input and store the information
user entered in a variable.
• The built-in function input can be used for this purpose:
<variable> = input(<prompt>)
• In Python 3, the input function always returns the
string type. E.g.
>>> num = input ("enter: ")
enter: 9
>>> type(num)
<class 'str'>
>>> num + 2
TypeError: can only concatenate str (not
"int") to str
10
User Input (cont)
To fix the error, use type casting functions such as int() or
float() to convert the string type to the required one
E.g.
>>> num = int ( input ("enter: ") )
enter: 9
>>> type(num)
<class 'int'>
>>> num + 2
11
Coding exercise: ask the user for a positive number (assume the user
always enters a valid/positive number), then your program outputs the
square and the square root of the number.
11
Conditional Statements
• A conditional statement lets us choose which
statement will be executed next
• Therefore they are sometimes called selection
statements, branching statements
• Conditional statements give us the power to make
basic decisions
• The conditional statements are :
– if statement
– if-else statement
– if-elif statement
12
Conditional Statements
The if Statement
• The if statement has the following syntax:
The condition must be a
boolean expression. It must
if is a Python evaluate to either True or False.
reserved word
if <condition>:
<body>
Indentation
matters!!
If the condition is true, the body is executed.
If it is false, the body is skipped.
13
Conditional Statements
The if-else Statement
• An else clause can be added to an if statement to make an if-
else statement
if <condition>:
<body1>
else:
<body2>
If the condition is true, body1 is executed; if the
condition is false, body2 is executed
One or the other will be executed, but not both
14
Conditional Statements
The if-elif Statement
• An elif clause can be added to an if statement to make an if-
elif statement
if <condition1>:
<body1>
elif <condition2>:
<body2>
If the condition1 is true, body1 is executed;
otherwise if the condition2 is true, body2 is executed
This structure can be followed by more elif clause or
else clause
15
Conditional Statements
Relational (Comparison) Operators
• A condition often uses one of the following
comparison operators, which all return boolean
results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
• Note the difference between the equality operator
( ==) and the assignment operator ( = )
16
Conditional Statements
Logical Operators
• There are three logical operators as follows:
not
and
or
• They all take boolean operands and produce boolean
results
• not is a unary operator (it operates on one operand)
• and and or are binary operators (each operates on
two operands)
17
Conditional Statements
Boolean Expressions
• A boolean expression is any expression that
evaluates to True or False
• Such expressions are often built from logical and
relational operators
• Use round brackets to make them clear, e.g.
(x < y) and (y < z)
18
Conditional Statements
Boolean Expressions (cont)
• Conditions can be complex expressions, e.g.
if total <= MAX and not found :
print("Processing…")
All logical operators have lower precedence than
the relational operators
Logical not has higher precedence than logical and
and logical or
19