L-2

Python Fundamentals:
Variables, Operators and Expressions

ENGG1330
Computer Programming I

HKU School of Computing and Data Science

We’re Starting at Different Levels

49% selected one of the two beginner options

Thought Python was about snakes
9%
Complete beginner
40%
Written a few small programs
37%
Comfortable coding independently
11%
Expert
2%
“I am Guido van Rossum”
1%

How Did Learning to Code Feel?

“Excited” was the most common response

22%excited
5%interesting
4%exciting
4%nervous
3%fun
3%hard
2%anxious
2%curious

Would You Press the Button?

A guaranteed B · No work · Nothing learned

86% chose “No”

No
86%
I’m torn
9%
Yes
6%
2

L-1 Participation Snapshot

Approximate figures reported by Kevin

Completed survey + challenge
≈30%
Completed only the survey
≈50%

The survey is only one part: remember the coding challenges too

3

Terminology

ENGG1330
Computer Programming 1

HKU School of Computing and Data Science
4

Terminology

We combine literals and variables with operators
to form expressions

5
Variables?
Operators?
Literals?
Expressions?

Terminology

pi = 3.14159diameter = 3area = pi * ( ( diameter / 2) ** 2 )print(area)
Download: engg1330.dirk.hk/lec_02_circle_area.py
6

Terminology

pi = 3.14159diameter = 3area = pi * ( ( diameter / 2) ** 2 )print(area)
Download: engg1330.dirk.hk/lec_02_circle_area.py

Literals

Raw data in code
7

Terminology

pi = 3.14159diameter = 3area = pi * ( ( diameter / 2) ** 2 )print(area)
Download: engg1330.dirk.hk/lec_02_circle_area.py

Variables

Remember stuff by storing it in memory
8

Terminology

pi = 3.14159diameter = 3area = pi * ( ( diameter / 2) ** 2 )print(area)
Download: engg1330.dirk.hk/lec_02_circle_area.py

Operators

Special symbols that carry out operations
9

Terminology

pi = 3.14159diameter = 3area = pi * ( ( diameter / 2) ** 2 )print(area)
Download: engg1330.dirk.hk/lec_02_circle_area.py

Expressions

Combine literals, variables and operators
10

Terminology

●Literals

○Raw data in code

●Variables

○Store data in memory

●Operators

○Special symbols that carry out operations

●Expressions

○Combine literals and variables to create new values

11

Literals

ENGG1330
Computer Programming 1

HKU School of Computing and Data Science
12

Literals Have Different Data Types

pi = 3.14159diameter = 3area = pi * ( ( diameter / 2) ** 2 )print(area)
Download: engg1330.dirk.hk/lec_02_circle_area.py
13
3
Integer (int)
3.14159
Float (float)
'Bruce Lee'
String (str)
True
Boolean (bool)

Variables

ENGG1330
Computer Programming 1

HKU School of Computing and Data Science
14

Variables Are Used to Store Data in Memory

a = 3b = 3.14159c = 'Bruce Lee'd = True
Download: engg1330.dirk.hk/lec_02_example_17_02.py
15

Variables Have Unique Names (Identifiers)

a = 3b = 3.14159c = 'Bruce Lee'd = True
Download: engg1330.dirk.hk/lec_02_example_17_02.py
16

Variables Have a Value

a = 3b = 3.14159c = 'Bruce Lee'd = True
Download: engg1330.dirk.hk/lec_02_example_17_02.py
17

Variables Have a Type

a = 3b = 3.14159c = 'Bruce Lee'd = True
Download: engg1330.dirk.hk/lec_02_example_17_02.py
18

Use type(x) to Determine the Type of the Variable x

a = 3b = 3.14159c = 'Bruce Lee'd = Trueprint(type(a))print(type(b))print(type(c))print(type(d))
Download: engg1330.dirk.hk/lec_02_example_21_03.py
19

You Can Also Directly Write the Literal in type(x)

print(type(3))print(type(3.14159))print(type('Bruce Lee'))print(type(True))
Download: engg1330.dirk.hk/lec_02_example_22_04.py
20

One Name Can Refer to Values of Different Types

age = 18print(type(age))       # intage = "18"print(type(age))       # str
Download: engg1330.dirk.hk/lec_02_value_types.py
21

Type Hints

: int documents the intended type

int(...) converts a value

Python does not enforce type hints at runtime

22

A Variable Is Like a Blackboard

age = 18print('You are', age)age = age + 1print('You will be', age, 'soon')
Download: engg1330.dirk.hk/lec_02_example_23_05.py
23

Names Describe What a Variable Is Used For

d = 7

elapsedTimeInDays = 7

24

Choosing Variable Names

Choose meaningful names that describe the value

elapsed_days = 7student_count = 120total_cost = 85.50

Start with a letter or underscore
Then use letters, digits or underscores

25

Valid and Invalid Names

InvalidReasonValid Alternative
2nd_scoreStarts with a digitsecond_score
classReserved keywordclass_name
total-costContains a hyphentotal_cost

Names are case sensitive
age and Age are different names

26

Identifiers Are Case Sensitive

27

Operators: Arithmetic

HKU School of Computing and Data Science
28

Arithmetic Operators

OperatorNameDescriptionExampleResult
+AdditionAdds the operands1 + 12
-SubtractionSubtracts the right operand5 - 41
*MultiplicationMultiplies the operands3 * 721
/DivisionDivides the left by the right3 / 60.5
%ModuloReturns the division remainder7 % 31
**ExponentRaises the left to a power7 ** 3343
//Floor DivisionRounds the quotient down7 // 32
29

Arithmetic Operators: Addition

numCookiesToday = 3numCookiesYesterday = 4print('You had',numCookiesYesterday + numCookiesToday,'total!')
Download: engg1330.dirk.hk/lec_02_example_37_09.py
30

Arithmetic Operators: Division

31

Modulus vs. Floor Division

32

Modulo: What Is Left Over?

7 objects, groups of 3

1 left over

33

Floor Division: How Many Complete Groups?

7 objects, groups of 3

2 complete groups

7Total=3Group size×2Complete groups+1Left over
34

Arithmetic Operators: Modulus

35

Modulo Checks Whether a Number Is Even or Odd

NumbersExamplesTest
Even2, 4, 6, 8, …x % 2 == 0
Odd1, 3, 5, 7, …x % 2 == 1
36

Operators: Assignment

HKU School of Computing and Data Science
37

Assignment Operator

38

Compound Assignment Operator

39

Complete the full survey during the lecture

40

Operators: Boolean and Comparisons
(If / Else)

HKU School of Computing and Data Science
41

Comparisons Produce Boolean Values

x = 42xMod2 = x % 2even = xMod2 == 0print(x,'is even:',even)
Download: engg1330.dirk.hk/lec_02_example_52_16.py
x = 43xMod2 = x % 2even = xMod2 == 0print(x,'is even:',even)
Download: engg1330.dirk.hk/lec_02_example_52_17.py
42

if Runs Code When Its Condition Is True

x = 42xMod2 = x % 2even = xMod2 == 0if even:  print(x,'is even:',even)
Download: engg1330.dirk.hk/lec_02_example_53_18.py
x = 43xMod2 = x % 2even = xMod2 == 0if even:  print(x,'is even:',even)
Download: engg1330.dirk.hk/lec_02_example_53_19.py
43

Branching with if and else

x = Trueif (x):    print('yes')else:    print('no')
Download: engg1330.dirk.hk/lec_02_example_54_20.py
x = Falseif (x):    print('yes')else:    print('no')
Download: engg1330.dirk.hk/lec_02_example_54_21.py
44

Indentation Marks Blocks of Code

x = Trueif (x):    print('yes')else:    print('no')
Download: engg1330.dirk.hk/lec_02_example_54_20.py
45

← A block of code

← Another block of code

Comparison Operators with if and else

x = 42xMod2 = x % 2if (xMod2 == 0):    print(x,'is even')else:    print(x,'is odd')
Download: engg1330.dirk.hk/lec_02_example_56_22.py
x = 43xMod2 = x % 2if (xMod2 == 0):    print(x,'is even')else:    print(x,'is odd')
Download: engg1330.dirk.hk/lec_02_example_56_23.py
46

Greater Than or Equal To

age = 17if (age >= 18):    print('You are an adult')else:    print('You are under age')
Download: engg1330.dirk.hk/lec_02_example_57_24.py
age = 36if (age >= 18):    print('You are an adult')else:    print('You are under age')
Download: engg1330.dirk.hk/lec_02_example_57_25.py
47

A Flowchart Shows the Program’s Logic

age>=18
adult
under age
True
False
age = 17if (age >= 18):    print('You are an adult')else:    print('You are under age')
Download: engg1330.dirk.hk/lec_02_example_57_24.py
48

Advanced Example

age within
[18, 25]?
True
No, Bye bye
height >= 180cm?
True
False
False
Yes, I do
49

Expressions

HKU School of Computing and Data Science
50

Parentheses Bind Operators and Operands Together

x = 42xMod2 = x % 2if (xMod2 == 0):    print(x,'is even')else:    print(x,'is odd')
Download: engg1330.dirk.hk/lec_02_example_56_22.py
x = 42if ((x % 2) == 0):    print(x,'is even')else:    print(x,'is odd')
Download: engg1330.dirk.hk/lec_02_example_61_26.py
51

Expressions - Example

52
My Mr. Right must be 18 or older and no older than 25 years old and his height must be at least 180cm
Let’s use a flow chart to screen potential boyfriends

Expressions - Example

age within
[18, 25]?

No, Bye bye

height >= 180cm?

True

False

True

False

Yes, I do

53

Combining Conditions in an Expression

age = 25height = 179if (((age >= 18) and (age <= 25)) and height >= 180):    print('Yes, I do')else:    print('No, Bye bye')
Download: engg1330.dirk.hk/lec_02_example_64_27.py
54

Which Operation Happens First?

Highest to Lowest

  1. **
  2. * / // %
  3. + -
  4. Comparisons
  5. not
  6. and
  7. or

Parentheses make the intended grouping explicit

55

Casting and
Square Bracket Operator

HKU School of Computing and Data Science
56

input() Returns a String

age = input('age: ')if (age >= 18):    print('You are an adult')else:    print('You are under age')
Download: engg1330.dirk.hk/lec_02_example_67_28.py
57

A String and an Integer Cannot Be Ordered

age = input('age: ')if (age >= 18):    print('You are an adult')else:    print('You are under age')
Download: engg1330.dirk.hk/lec_02_example_67_28.py
58

Converting Values to a Different Type

ConversionResulting Type
int(x)Integer
str(x)String
float(x)Float
59

int() Converts the Input to an Integer

age = input('age: ')print(type(age))age = int(age)print(type(age))if (age >= 18):    print('You are an adult')else:    print('You are under age')
Download: engg1330.dirk.hk/lec_02_example_70_29.py
60

Accessing String Characters by Index

Python uses zero-based indexing

ExpressionCharacter
s[0]First
s[1]Second
s[-1]Last
s[-2]Second last

Keep the index within the string’s bounds

61

Accessing Characters by Index

name = input('name: ')index = int(input('index: '))print(name[index])
Download: engg1330.dirk.hk/lec_02_example_72_30.py
62

To Earn Your Participation Mark

  • Complete the full survey during the lecture
  • Pass all tests in at least 2 of the 3 challenges
    by 23:59 HKT today

Both required · 1 mark · No partial credit

63