Chapter 2 PythonBasics
Chapter 2 PythonBasics
Python Basics
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim ([email protected]) & Dr. H.F. Ting ([email protected])
Department of Computer Science, The University of Hong Kong
Values and variables
Some commonly used simple values
E.g.
bool Boolean values True, False
int Integers -4, 0, 65
float Real numbers -2.36, 6.0e5, 7e-2
str Character strings "abcde", 'abcde', "ab'cde", 'ab"cde'
2
Values and variables
Some commonly used simple values
E.g.
bool Boolean values True, False
int Integers -4, 0, 65
float Real numbers -2.36, 6.0e5, 7e-2
str Character strings "abcde", 'abcde', "ab'cde", 'ab"cde'
3
Referring to a value
After a long and difficult computation, you have got an important value.
Then, you can give this value some "name", and in the rest of your program,
you can use this "name" to refer to this value.
Example
4
Rules for naming a variable
Variables names must start with a letter or an underscore, such as:
_underscore but not the numbers
temperature
The remainder of your variable name may consist of letters, digits
and underscores.
password1
n00b
un_der_scores
_ooOoo_
Names are case sensitive.
case_sensitive, CASE_SENSITIVE, and Case_Sensitive are different variable
names.
5
Rules for naming a variable
There are some "reserved" words (keywords) in Python that
cannot be used as variable names.
6
Rules for naming a variable
There are some "reserved" words (keywords) in Python that
cannot be used as variable names.
7
Type Casting
You can convert a value from one type to another type.
We can use input() to read a string from the keyboard, and give this string a
name.
9
Input()
We can use input() to read a string from the keyboard, and give this string a
name.
prompt
message
<—how( become string)
to help
user
10
Input()
What should we do if we want to input an integer (or a float number)?
Use type casting
11
Sequence of values: Lists and Tuples
list: A sequence of values (can be of different types)
Examples:
[1, 30, 25, 100]
['A', 'B', 'C', 'D', 'E']
[[1,2,3], "happy", 40.0, True]
After associating a list with some name, we can access each entry in the list by
indexes: the 1st entry has index 0, the 2nd index 1, ..., the last index lenght-1, where
length is total number of entries in the list.
12
Sequence of values: Lists and Tuples
We can change the value of any entry in a list.
13
Sequence of values: Lists and Tuples
You can construct a table using list.
Example: Construct the following table T:
0 1 2
3 4 5
6 7 8
14
In class exercise
A magic square is a 3x3 table with nine distinct integers from 1
to 9 so that the sum of integers in each row, column, and
corner-to-corner diagonal is the same.
An example
2 7 6
9 5 1
4 3 8
15
A useful way to solving the problem
#create a 3 x 3 table T. Don’t worry how to do it at the moment.
#input entries of the table
why
T[0][0]=int(input())
T[0][1]=int(input())
T[0][2]=int(input())
…
T[0][0] T[0][1] T[0][2]
#print sums
T[1][0] T[1][1] T[1][2]
print(T[0][0]+T[0][1]+T[0][2]) T[2][0] T[2][1] T[2][2]
…
print(T[0][0]+T[1][1]+T[2][2])
print(T[0][2]+T[1][1]+T[2][0]
16
How to create a 3x3 table
#method 1
T=[[0,0,0],[0,0,0],[0,0,0]]
#==================================
#method 2
T=[]
T.append([0,0,0]) 0 0 0
T.append([0,0,0]) 0 0 0
T.append([0,0,0]) 0 0 0
#==================================
#method 3
R = [0,0,0]
T = []
T.append(R)
T.append(R)
T.append(R)
17
How to create a 3x3 table
#method 1
T=[[0,0,0],[0,0,0],[0,0,0]]
#==================================
#method 2
T=[]
T.append([0,0,0]) 0 0 0
T.append([0,0,0]) 0 0 0
T.append([0,0,0]) 0 0 0
#==================================
#method 3
X
R = [0,0,0]
T = []
T.append(R)
T.append(R)
T.append(R) Method 3 is wrong. Why?
18
How to create a 3x3 table
# Try this
R = [0,0,0]
T = []
T.append(R)
T.append(R)
T.append(R)
print(T)
T[1][1] = 7
print (T)
19
How to create a 3x3 table
# Try this [0, 0, 0]
R = [0,0,0] R=
T = []
T.append(R) T=[ , , ]
T.append(R)
T.append(R)
print(T) There is only one R list in the main memory.
T[1][1] = 7 When we append R to T, it simply append a
pointer to R to T.
print (T)
20
How to create a 3x3 table
# Try this [0, 0, 0]
R = [0,0,0] R=
T = []
T.append(R) T=[ , , ]
T.append(R)
T.append(R) After T[1][1]=7
print(T)
T[1][1] = 7 [0, 7, 0]
print (T) R=
T=[ , , ]
X
#method 3 #method 4
R = [0,0,0] R = [0,0,0]
T = []
T = [R, R, R]
T.append(R)
T.append(R)
T.append(R) Method 4 is wrong because of
the same reason!
22
How to create a 3x3 table
Advice for beginners: Use actual values.
#method 1
T=[[0,0,0],[0,0,0],[0,0,0]]
#==================================
#method 2
T=[]
T.append([0,0,0])
T.append([0,0,0])
T.append([0,0,0])
23
A program that does not follow my
advice, but is still correct
24
Sequence of values: Lists and Tuples
tuple: A sequence of values (can be of different types) like list. But you cannot
make any change to it. tuple can be viewed as a constant list.
Examples:
([1,2,3], "happy", 40.0, True)
After associating a tuple with some name, we can access the entries in the list by
indexes: the 1st entry has index 0, the 2nd index 1, ..., the last index lenght-1, where
length is total number of entries in the list.
For tuple, you can omit the
parentheses.
Example:
mytuple = 'a', 'b', True, 54
25
Sequence of values: Lists and Tuples
Our old friend str can be viewed as a special case of tuple, in which all
entries are characters.
26
type() and type casting for list, tuple and string
27
Set
A collection of values (or you may view set as a sequence of values, but
without order)
28
Set
Set membership testing: the in operator
tuple can be an
element,
list cannot be an
element because we
have no way to
locate and update
the list
29
Set
Add elements to a set
30
Dictionary
A set of key:value pairs. Again, the entries do not have order.
32
Summary
bool True, False
int 34, -41
float 34.5, -3.14e7
str "Peter", 'Mary'
list a = [1, 'h', [6, 7,8]] ➔ a[0], a[1], a[2] list & tuple are
t = ('a','b',22,[True,False]) ➔ t[0], t[1], t[2], t[3] known as sequences
tuple
set s = {1, 'a', ("Hello", 4)} ➔ s[0]
dictionary d = {"Peter":100, "Mary":89} ➔ d["Peter"]
33
Expressions
Definitions on operators and operands
Operators for simple values
Arithmetic operators
Relational (Comparison) operators
Logical operators
Membership operators
Operators for sequences of values (i.e., for lists, tuples, and
strings, but not for dictionaries and sets)
Concatenator +
Repeat *
Relational (Comparison) operators
34
Arithmetic
E.g., a = 10, b = 20
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power
20
// Floor Division - The division of operands where the 9 // 2 = 4
result is the quotient in which the digits after the 9.0 // 2.0 = 4.0
decimal point are removed. But if one of the operands is -11 // 3 = -4
negative, the result is floored, i.e., rounded away from -11.0 // 3 = -4.0
zero (towards negative infinity) −
35
Relational (Comparison)
E.g., a = 10, b = 20
== If the values of two operands are equal, then the condition (a == b) is not true.
becomes true.
!= If values of two operands are not equal, then condition becomes (a != b) is true.
true.
> If the value of left operand is greater than the value of right (a > b) is not true.
operand, then condition becomes true.
< If the value of left operand is less than the value of right operand, (a < b) is true.
then condition becomes true.
>= If the value of left operand is greater than or equal to the value of (a >= b) is not true.
right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of (a <= b) is true.
right operand, then condition becomes true.
36
Logical
E.g., A = True, B = False
and True if both operands are True, and False A and B = False
otherwise
Membership
in Evaluates to true if it finds a variable in
x in y, here in results is a 1 if
the specified sequence and false
x is a member of sequence y.
otherwise.
not in Evaluates to true if it does not find a x not in y, here not in results
variable in the specified sequence and is a 1 if x is not a member of
false otherwise. sequence y.
37
Operator Description
Low
or Boolean OR
and Boolean AND
not x Boolean NOT
Comparisons, including membership
<, <=, >, >=, !=, ==
tests and identity tests
+, - Addition and subtraction
Multiplication, matrix multiplication,
*, /, //, %
division, floor division, remainder
+x, -x Positive, negative
High
** Exponentiation
38
operator + for combining two sequences
2 tuples
2 lists
1 tuple & 1 list
39
Operator * for repeating a sequence
40
Comparison operators on sequences
Lexicographical (dictionary) order on sequences
Given two sequences a, b of equal length.
a == b if both sequences have the same values at the same position.
a < b if at the first position where a and b have different values, a’s value is
smaller than b’s.
When a and b have different lengths. Suppose with loss of generality
that a is the shorter sequence. Then let a’ be the sequence of a
appended with the NULL values so that the length of a’ and b are equal.
Here, NULL is smaller than any other value. Then
a < b if and only if a’ < b.
[4, 5, 6] < [4, 3, 100]: False
[4, 5, 6] < [4, 5, 6, 7]: True (because [4, 5, 6, NULL] < [4, 5, 6, 7])
41
在输出中,\t 在 "Hello" 和 "World!" 之间插
⼊了⼀段⽔平间距,使得它们在显示时对
⻬到下⼀个制表位
Special characters
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL) appears as a space
\b ASCII Backspace (BS) appears as a space
\f ASCII Formfeed (FF) appears as a space
\n ASCII newline goes to a new line
\r ASCII Carriage Return (CR) appears as a space
\t ASCII Horizontal Tab (TAB) equivalent to “tab” button
\v ASCII Vertical Tab (VT) appears as horizontal tab
42
Some more examples
43
Example
44
raw string
You can ask Python to ignore special characters by using raw-
string.
You create a raw string using r.
45
sep (separator) & end for print
46
f-string
A new feature introduced in Python 3.6
It provides a simple way to substitute values into strings.
Example:
No need to use , and ‘ / “ to compose
the string. Instead, we use {} to enclose a
variable.
END
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim ([email protected]) & Dr. H.F. Ting ([email protected])
Department of Computer Science, The University of Hong Kong