HO CHI MINH CITY UNIVERSITY OF TRANSPORT
FACULTY OF INFORMATION TECHNOLOGY
SOFTWARE ENGINEERING DEPARTMENT
CHAPTER 5
ELEMENTARY PROGRAMMING
1
CONTENTS
Keywords Identifier Data Types Variables
Assignment
Constants Expressions Operators
Statement
Data Type
Statements Indentation Comments
Conversion
2
Writing a Simple Program
• Problem: Calculating the area of a circle.
• Algorithm:
1. Get the circle’s radius from the user.
2. Compute the area by applying the following formula:
area = radius * radius * PI
3. Display the result.
• Important issues:
• How to read the radius?
• How to store the radius, area in the program?
• Values for the radius and area are stored in the computer’s
memory
• How to display result?
3
Writing a Simple Program
• Program
4
Keywords
• Keywords that are reserved words, have special meanings.
They cannot be used as variable names, function names, or
any other identifiers.
and else in return
as except is True
assert False lambda try
break finally None while
class for nonlocal with
continue from not yield
def global or
del if pass
elif import raise
5
Identifier
• Identifier is the name that identify the element in a program
such as variable, function, array….
• All identifiers must obey the following rules:
• Consists of letters, digits, and underscores (_)
• Must start with a letter or an underscore, cannot start with a
digit
• Cannot be a keyword
• Can be of any length
• Example:
• Legal identifiers: area, radius, top_of_page, temp1…
• Not legal identifiers: 2A, for, search elem
6
Identifier
• Note:
• Python is case sensitive → area, Area, and AREA are all
different identifiers
• Tip:
• Descriptive identifiers → easy to read, understand, maintain
• Use lowercase letters for variable names
• Two major ways to paste words together:
• Underscore: radius_of_circle
• Camel Case: radiusOfCircle
• Quiz:
• Which of the following identifiers are valid?
miles, Test , a+b, b–a, 4#R, $4, #44, if
7
Data Types
• A data type consists of two things:
• A set of values it can have
• A set of operations that can be performed on those values
• Basic data types:
• Integer
• Floating-Point Number
• Complex Number
• String
• Boolean
8
Data Types
1. Integer
• Contains values: -3, 3, 0, -1, 1234,…
• Type: int
• An integer value in other bases
Prefix Base
0b (zero + 'b') 2
0B (zero + 'B')
0o (zero + 'o') 8
0O (zero + 'O')
0x (zero + 'x') 16
0X (zero + X')
9
Data Types
2. Floating-Point Number
• Contains real values with a decimal point: -3.5, 3.1419, 4.2e-
4…
• Type: float
• Precision: float values are only approximations to real
numbers.
10
Data Types
3. Complex Number
• Complex numbers are specified as <real part> + <imaginary
part>j
• Type: complex
11
Data Types
4. String
• String is sequence of character
data.
• Type: str
• String literals may be delimited
using either single or double
quotes
• ‘Hello’
• “Hello”
• A string can also be empty: ‘’
• To include special character in a
string → using a backslash (\)
12
Data Types
4. String
Special Character
Escape Example
Sequence
\'
\"
\newline
\\
13
Data Types
4. String
Applying Special Meaning to Characters
Escape Interpretation
Sequence
\t Horizontal Tab (TAB) character
\n New line
\a Bell (BEL) character
\b Backspace character
\r Carriage Return (CR) character
14
Data Types
4. String
Example:
15
Data Types
5. Boolean
• Boolean type may have one of two values, True (1) or False
(0)
• Type: bool
• Expressions are often evaluated in Boolean context.
16
Variables
• Variables are the names that refers to different values stored in memory.
Every value has a data type.
• Naming variables must follow the rules of identifiers.
• Variable Creation
• Assign values to a variable
variable = expression
• ‘=’ : gets, not equals
• We can reassign the value of a variable
17
Variables
A variable must be
• NOTE: created before it can
be used.
Must place the variable
name to the left of the
assignment operator
18
Variables
• NOTE: radius 1.5
Python is a dynamically typed language
2
Dynamic Typing
• Interpreter does type checking
only as code runs
• Type of a variable is allowed to
change over its lifetime
Static Typing
• Type checking is performed as
your program is compiled
• A variable generally is not
allowed to change type.
19
Variables
Object References
• Python is a highly object-oriented language → every item of
data in a Python program is called an object.
• Objects can be very small (the number 3) or very large (a
digital photograph)
• Every object stored in memory location.
radius PyFloatObject {
value = 1.5
}
PyIntObject {
value = 2
}
20
Variables
Object References
x PyIntObject {
value = 7
}
y PyIntObject {
value = 3
}
PyStrObject {
value = “abc”
}
• There is no longer any reference to the integer object with value 7.
What happens with this object???
21
Variables
• NOTE:
Lifetime of an object
• An object’s life begins when it is created, at which time at
least one reference to it is created.
• When there is no reference to object:
→ lifetime is over
→ it is inaccessible
→ reclaim the allocated memory (garbage collection)
22
Assignment Statement
• The general syntax:
variable = expression
• This is executed as follows:
1. Evaluate the expression to produce a value.
2. Assign value of expression to variable.
• An expression represents a computation involving values, variables,
and operators that, taken together, evaluate to a value.
23
Assignment Statement
• Syntax to assgin a value to multiple variables :
var1 = var2 =…varn = expression
• Example:
i=j=k=1
equivalent to
k=1
j=k
i=j
24
Assignment Statement
• Syntax of Simultaneous Assignment:
var1, var2, ..., varn = exp1, exp2, ..., expn
• Evaluate all the expressions on the right and assign them to the
corresponding variable on the left simultaneously.
Using temporary variable Using simultaneous assignment
25
Assignment Statement
• Simultaneous Assignment
Example: Input three numbers and obtains their average.
26
Constants
• A constant is an identifier that represents a permanent value
(never change).
• Python does not have a special syntax for constants
→Create a variable to denote a constant.
→To distinguish a constant from a variable, use all uppercase
letters to name a constant
• Example: PI = 3.14159
• Benefits of using constants:
1. Don’t have to repeatedly type the same value if it is used
multiple times.
2. If you have to change the constant’s value, only need to
change it once.
3. Descriptive names make the program easy to read.
27
Expressions
• An expression is a combination of zero or more operators
and one or more operands.
• Operands: constants, variables, function calls.
• Operators: are special tokens that represent computations.
• The interpreter evaluates expression → produces a value.
• Example:
• 42, n, print(“hello”)
• 3*((i % 4)*(5 +(j – 2)/(k+3)))
• x >= y
• x >= 0 and y >= 0
28
Operators
• Operators are used to perform operations on variables and
values.
• Python divides the operators in the following groups:
• Arithmetic operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
• Assignment operators
29
Arithmetic operators
Arithmetic operators are used to perform common mathematical operations:
Operator Meaning Types of Operands Example
9 + 4 → 13 , 9 + 4.5 → 13.5
(2 + 3j) + (3 + 3j) →(5+6j)
int, float, complex, str,
+ Addition ‘yo’ + ‘u’ → ‘you’
bool
True + False → 1
True + True → 2
9 - 4 → 5 , 9 - 4.5 → 4.5
int, float, complex,
- Subtraction (3 +3j) – (2+3j) → (1 +0j)
bool
True - False → 1
9*4.5 → 40.5
(2 + 3j) * (3 + 3j) → (-3+15j)
int, float, complex,
* Multiplication (2 + 3j) *9 → (18+27j)
str, bool
True * False → 0
‘you‘ * 3 → 'youyouyou'
30
Arithmetic operators
Operator Meaning Types of Operands Example
9 / 4 → 2.25, 9 / 4.5 → 2.0
/ Float Division int, float, complex
(1 + 2j) / (4 + 2j) → (0.4+0.3j)
9 // 4 → 2
// Integer Division int, float
9 // 4.5 → 2.0
Modulus: 9%4→1
% returns the int, float 9.5 % 4 → 1.5
remainder
4 ** 0.5 → 2.0
** Exponentiation int, float, complex 4.5 ** 3 → 91.125
(1+2j) ** 2 → (-3+4j)
31
Comparison Operators
• Comparison operators are used to compare two values.
• It either returns True or False
Types of
Operator Syntax Meaning Example
Operands
1 == 2 → False
int, float,
== a == b Equal "he" == "He" → False
complex, str
1.1 + 2.2 == 3.3 →False
int, float, 3 != 3.0 → False
!= a != b Not equal
complex, str (1+2j) != (4+2j) → True
> a>b Greater than int, float, str 7 > 5 → True
< a<b Less than int, float, str 'he' < 'an‘ → False
>= a >= b Greater than or equal to int, float, str 100 >= 100 → True
<= a <= b Less than or equal to int, float, str 100 <= 50 → False
32
Logical Operators
• Logical operators are used to combine comparison
expression.
• Type of Operands is bool.
• It either returns True or False
Operator Syntax Meaning Example
((9/3 == 3) and (2*3 ==6))
True if both a and b are True → True
and a and b
False otherwise (('A'== 'a') and (3==3))
→ False
True if either a or b is True ((2==3) or ('A'=='A'))
or a or b
False otherwise → True
True if x is False
not not a not(3 == 3) → False
False if x is True
33
Logical Operators
NOTE: Evaluation of Non-Boolean Operands
• Numeric Value
• A zero value is False.
A non-zero value is True.
• String
• An empty string is False.
A non-empty string is True.
• Composite Object: list, tuple, dict, and set
• False if it is empty and True if it is non-empty
• “None” Keyword
34
Logical Operators
NOTE: Evaluation of Non-Boolean Operands
a b a and b a or b not a
True True/False b a False
False True/False a b True
Compound Syntax Meaning Result
or x1 or x2 or … xn True if any of the - First xi is True
xi are True - xn otherwise
and x1 and x2 and … xn True if all the xi - xn if all the xi are
are True True
- First xi is False
35
Identity Operators
• Identity operators are used to compare the objects
• not if they are equal, but if they are actually the same object,
with the same memory location
Operator Syntax Meaning
Returns true if both
is a is b variables are the same
object
Returns true if both
is not a is not b variables are not the
same object
36
Membership Operators
• Membership operators are used to test whether a value or
variable is in a sequence.
Operator Syntax Meaning
Returns True if a
sequence with the
In a in b
specified value is
present in the object
Returns True if a
sequence with the
not in a not in b
specified value is not
present in the object
37
Bitwise Operators
• Bitwise operators are used to compare (binary) numbers.
Operator Syntax Meaning Example
& a& b Bitwise AND print(10 & 4) → 0
| a|b Bitwise OR print(10 | 4) → 14
^ a^b Bitwise XOR print(10 ^ 4) → 14
~ ~a Bitwise NOT print(~10) → -11
>> a >> b Bitwise right shift print(10 >> 2) → 2
<< a << b Bitwise left shift print(10<<2) → 40
38
Assignment operators
Assignment operators are used to assign values to variables:
Operator Syntax Equivalent Operator Syntax Equivalent
= a=b a=b &= a &= b a=a&b
+= a += b a=a+b |= a |= b a=a|b
-= a -= b a=a–b ^= a ^= b a=a^b
*= a *= b a=a*b >>= a >>= b a = a >> b
/= a /= b a=a/b <<= a <<= b a = a << b
%= a %= b a=a%b
//= a //= b a = a // b
**= a **= b a = a ** b
39
Operator Precedence
Order Operator Order Operator
1 or 9 +, -
2 and 10 *, /, //, %
3 not x 11 +x, -x, ~x
in, not in, is, is not, <, <=,
4 12 **
>, >=, !=, ==
x[index], x[index:index], x(arg
5 | 13
uments...), x.attribute
6 ^ (expressions...),
14 [expressions...], {key: value...}
7 & , {expressions...}
8 <<, >>
Note: 1 - lowest precedence , 14 - highest precedence
40
Data Type Conversion
• Data Type Conversion can happen in two ways:
• Implicit
• Explicit (type casting)
Required_data_type (expression)
41
Statements
• Programs are made up of statements, or instructions
• Statements are divided into 2 types:
• Simple statements
• Function calls
• Assignment statements
• Statements: break, continue, return
• …
• Compound statements
• Contain other statements
• Affect or control the execution of those other statements
• Such as: if , for, while, try, with,…
42
Indentation
• Block of statements:
• Grouping of statements for a specific purpose
• Most of the programming languages like C/C++, Java use braces { } to
define a block of statements
• Python uses indentation to highlight the block
• Whitespace is used for indentation
• A block starts with indentation and ends with the first unindented line
• All statements with the same distance to the right belong to the same
block
43
Comments
• Comments can be used to:
• Explain Python code that may not be easy to understand
• Make the code more readable
• Prevent execution when testing code.
• Comments are not compiled and executed
• Creating a Comment:
• Using # for single line
• Using triple quotes (multiline string) for multi-line
44
Comments
45