Nhập môn lập trình
GV: Hoàng Đức Quý – BM. ĐTVT
Variables, Expressions, and
Statements
Chapter 2
Creative Commons Attribution 3.0 License
Copyright 2010- Charles Severance
These slides are a derivative work based on the original slides, “Python for Informatics :
Exploring Information”, created by Charles Severance. The original slides are located at
www.pythonlearn.com
This modified set of slides was done by John Alexander (2013).
The primary purpose of this derivative work is to make the highest quality Python courseware
available to instructors so that they can teach Python, and insure that the slides are properly
formatted for easy, out-of-the-box, use by both Microsoft PowerPoint and OpenOffice Impress.
Unless otherwise noted, the content of this course material is licensed under a Creative
Commons Attribution 3.0 License (The “BY” variant of the license)
http://creativecommons.org/licenses/by/3.0/.
Constants
• Fixed values such as numbers, letters, and
strings are called “constants” - because their
value does not change
• Numeric constants are as you expect
• >>>
String constants use single-quotes
123
(') print 123
or double-quotes (")
>>> print 98.6
98.6
>>> print 'Hello world
Hello world
Variables
• A variable is a named place in the memory where a
programmer can store data and later retrieve the data
using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later
statement
x = 12.2 x 12.2100
y = 14
x = 100 y 14
Python Variable Name Rules
• Can consist of letters, numbers, or underscores (but
cannot start with a number)
• Case Sensitive
• Good: spam eggs spam23 _speed
• Bad: 23spam #sign var.12
• Different: spam Spam SPAM
Reserved Words
• You can NOT use reserved words as variable names /
identifiers
and del for is raise assert elif
from lambda return break else
global not try class except if or while
continue exec import pass
yield def finally in print
Statements
x=2 Assignment Statement
x=x+2 Assignment with expression
print x Print statement
Variable Operator Constant Reserved Word
Assignment Statements
• We assign a value to a variable using the assignment
statement (=)
• An assignment statement consists of an expression on
the right hand side and a variable to store the result
x = 3.9 * x * ( 1 - x )
A variable is a memory
location used to store a x 0.6
value (0.6).
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
Right side is an expression.
Once expression is 0.936
evaluated, the result is
placed in (assigned to) x. x 0.936
A variable is a memory
location used to store a
value. The value stored in a x 0.6 0.93
variable can be updated by
replacing the old value (0.6)
with a new value (0.93).
x = 3.9 * x * ( 1 - x )
Right side is an expression.
Once expression is
evaluated, the result is 0.93
placed in (assigned to) the
variable on the left side (i.e.
x).
Numeric Expressions
• Because of the lack of
mathematical symbols on
computer keyboards - we use + Addition
“computer-speak” to express - Subtraction
the classic math operations Multiplicatio
*
n
• Asterisk is multiplication
/ Division
• Exponentiation (raise to a ** Power
power) looks different from in % Remainder
math.
Numeric Expressions
>>> x = 2 >>> j = 23
>>> x = x + 2 >>> k=j%5 + Addition
>>> print x >>> print k
- Subtraction
4 3 Multiplicatio
*
>>> y = 440 * 12 >>> print 4 ** 3 n
>>> print y 64 / Division
5280 4R3 ** Power
Remainder
>>> z = y / 1000 5 23
%
(Modulus)
>>> print z 20
5
3
Order of Evaluation
• When we string operators together - Python must know
which one to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
• Highest precedence rule to lowest precedence rule
• Parenthesis are always respected
• Exponentiation (raise to a power) Parenthesis
Power
• Multiplication, Division, and Remainder Multiplication
Addition
Left to Right
• Addition and Subtraction
• Left to right
x = 1 + 2 ** 3 / 4 * 5
Parenthesis
Power
Multiplication
Addition
Left to Right
x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
1+8/4*5
Note 8/4 goes before 1+2*5
4*5 because of the
left-right rule.
Parenthesis 1 + 10
Power
Multiplication
Addition
Left to Right
11
Operator Precedence Parenthesis
Power
Multiplication
• Remember the rules -- top to bottom Addition
Left to Right
• When writing code - use parenthesis
• When writing code - keep mathematical expressions
simple enough that they are easy to understand
• Break long series of mathematical operations up to
make them more clear
Exam Question: x = 1 + 2 * 3 - 4 / 5
Integer Division
>>> print 10 / 2
5
>>> print 9 / 2
• Integer division truncates 4
>>> print 99 / 100
• Floating point division 0
produces floating point >>> print 10.0 / 2.0
numbers 5.0
>>> print 99.0 / 100.0
0.99
This changes in Python 3.0
Mixing Integer and Floating
Numbers in Arithmetic
Expressions
• When you perform an
operation where one >>> print 99 / 100
operand is an integer 0
and the other operand >>> print 99 / 100.0
is a floating point the 0.99
result is a floating >>> print 99.0 / 100
point 0.99
>>> print 1 + 2 * 3 / 4.0 - 5
• The integer is -2.5
converted to a floating >>>
point before the
operation
Some Data Types in Python
• Integer (Examples: 0, 12, 5, -5)
• Float (Examples: 4.5, 3.99, 0.1 )
• String (Examples: “Hi”, “Hello”, “Hi there!”)
• Boolean (Examples: True, False)
• List (Example: [ “hi”, “there”, “you” ] )
• Tuple (Example: ( 4, 2, 7, 3) )
Data Types In C/C++:
• In Python variables, int a;
literals, and constants float b;
have a “data type” a=5
b = 0.43
• In Python variables are
“dynamically” typed. In In Python:
some other languages you
have to explicitly declare a=5
the type before you use a = “Hello”
the variable a = [ 5, 2,
1]
• More on “Types”
In Python variables,
literals, and constants
have a “type”
>>> d = 1 + 4
• Python knows the >>> print d
difference between an 5
integer number and a
string >>> e = 'hello ' + 'there'
>>> print e
• For example “+” means hello there
“addition” if something is
a number and concatenate = put together
“concatenate” if
>>> e = 'hello ' + 'there'
Type Matters >>> e = e + 1
Traceback (most recent call
• Python knows what “type” last):
everything is File "<stdin>", line 1, in
<module>
• Some operations are TypeError: cannot
concatenate 'str' and 'int'
prohibited
objects
• You cannot “add 1” to a >>> type(e)
<type 'str'>
string
>>> type('hello')
• We can ask Python what <type 'str'>
>>> type(1)
type something is by using
the type() function. <type 'int'>
>>>
Several Types of Numbers
• Numbers have two main types
>>> x = 1
>>> type (x)
• Integers are whole numbers: -
<type 'int'>
14, -2, 0, 1, 100, 401233
>>> temp = 98.6
>>> type(temp)
• Floating Point Numbers have
<type 'float'>
decimal parts: -2.5 , 0.0, 98.6,
>>> type(1)
14.0
<type 'int'>
>>> type(1.0)
• There are other number types - <type 'float'>
they are variations on float and >>>
integer
Type >>> print float(99) / 100
Conversions 0.99
>>> i = 42
• When you put an integer >>> type(i)
<type 'int'>
and floating point in an
expression the integer is >>> f = float(i)
implicitly converted to a >>> print f
float 42.0
>>> type(f)
• You can control this with <type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
the built in functions int()
and float() -2.5
>>>
String >>> sval = '123'
>>> type(sval)
<type 'str'>
Conversions >>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• You can also use int() TypeError: cannot concatenate 'str'
and float() to convert and 'int'
between strings and >>> ival = int(sval)
integers >>> type(ival)
<type 'int'>
>>> print ival + 1
• You will get an error if 124
the string does not >>> nsv = 'hello bob'
contain numeric >>> niv = int(nsv)
characters Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
User Input
• We can instruct
Python to pause
and read data from
the user using the name = raw_input(‘Who are you?’)
raw_input() print 'Welcome ', name
function
• The raw_input()
Who are you? Chuck
function returns a
string Welcome Chuck
Converting User
Input
•If we want to read a
number from the
user, we must inp = raw_input(‘Europe floor?’
convert it from a usf = int(inp) + 1
string to a number print “US floor: ”, usf
using a type
conversion function
Europe floor? 0
• Later we will deal
US floor : 1
with bad input data
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
• Describe what is going to happen in a sequence of
code
• Document who wrote the code or other ancillary
information
• Turn off a line of code - perhaps temporarily
# Get the name of the file and open it
name = raw_input("Enter file:")
handle = open(name, "r") # This is a file handle
text = handle.read()
words = text.split()
String Operations
• Some operators apply to
strings
• + implies >>> print 'abc' + '123‘
Abc123
“concatenation”
• * implies “multiple >>> print 'Hi' * 5
concatenation” HiHiHiHiHi
• Python knows when it is
dealing with a string or a
number and behaves
appropriately
Mnemonic Variable
Names
• Since we programmers are given a choice in
how we choose our variable names, there is a
bit of “best practice”
• We name variables to help us remember what
we intend to store in them (“mnemonic” =
“memory aid”)
• This can confuse beginning students because
well named variables often “sound” so good
that they must be keywords
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c=a*b
print x1q3p9afd print c
hours = 35.0
What is this rate = 12.50
code doing? pay = hours * rate
print pay
Exercise
Write a program to prompt the user for
hours and rate per hour to compute gross
pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Summary
• Types (int, float, boolean, string, list, tuple, …)
• Reserved words
• Variables (mnemonic)
• Operators and Operator precedence
• Division (integer and floating point)
• Conversion between types
• User input