0% found this document useful (0 votes)
26 views

Chapter 2 PythonBasics

R1 = [0,0,0] R2 = [0,0,0] R3 = [0,0,0] T = [R1, R2, R3] This program creates a 3x3 table T by initializing 3 separate list objects R1, R2, R3 and appending them to the list T. Though it does not follow the advice to use actual values, it still correctly creates 3 independent lists in memory without referencing the same list object multiple times.

Uploaded by

cjq1222
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Chapter 2 PythonBasics

R1 = [0,0,0] R2 = [0,0,0] R3 = [0,0,0] T = [R1, R2, R3] This program creates a 3x3 table T by initializing 3 separate list objects R1, R2, R3 and appending them to the list T. Though it does not follow the advice to use actual values, it still correctly creates 3 independent lists in memory without referencing the same list object multiple times.

Uploaded by

cjq1222
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Chapter 2.

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'

You can use type() to find out the


type of a value.
Also note the different colors.

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

From now on, you can use BMI to refer to


BMI 22.49
the value 22.49, until you associate BMI
with another value.
Sometimes, we say that BMI is a variable. The above diagram reminds us that BMI
is referring to the value 22.49

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.

this list need to be remenber for the final exam

6
Rules for naming a variable
 There are some "reserved" words (keywords) in Python that
cannot be used as variable names.

There are other words that are not keywords,


but you should avoid using them as variable
names, e.g., input, print, type, which are names
of some “build-in” functions.

7
Type Casting
 You can convert a value from one type to another type.

Warning: Make sure you know the


difference between
True and "True".
8
Input() always give the string

 We can use input() to read a string from the keyboard, and give this string a
name.

Regardless of what you’ve


typed, your input always
forms a string.

9
Input()
 We can use input() to read a string from the keyboard, and give this string a
name.

Regardless of what you’ve


typed, your input always
forms a string.

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.

mylist[0] mylist[1] mylist[2] mylist[3]

12
Sequence of values: Lists and Tuples
 We can change the value of any entry in a list.

 We can append a new entry to 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

 Exercise: Write a Python program that reads a 3x3 table and


prints the sum of integers in each row, column, and corner-to-
corner diagonal.

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=[ , , ]

We follow the pointer, access and update R.


21
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
#================================== #==================================

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

R1, R2 and R3 are 3 different lists in the main memory.

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

Note the difference between


a = 1,
and
a=1

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

list(A): cast A into a list


tuple(B): cast B into a tuple
str(C): cast C into a string

27
Set
 A collection of values (or you may view set as a sequence of values, but
without order)

 As there is no order, we cannot refer its entries by indexes.

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.

Given a key, we can access


the corresponding value.

Add a new key:value pair


to the dictionary

How about this? phonelist[“Tim”]=“abcde”


Yes, it’s correct. The type of entry doesn’t matter.
31
A more complicated example

The key must be enclosed using single quotes or


double quotes.

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

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% 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

or False if both operands are False, and True A or B = True


otherwise

not True if operand is False, and False if not A = False


operand is True not B = True

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

Only for sequences (list & tuple)

39
Operator * for repeating a sequence

 Repeat a tuple 4 times

 Repeat a list 4 times

 Repeating a set is not allowed!!!

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

sleep(1) → pause for 1 second

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

Default: sep=‘ ‘ (space), and end='\n’ (new line)

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.

The string in {} is treated as an


ordinary expression,
and Python will print the result
of this expression
in the f-string. 47
Chapter 2.

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

You might also like