ENGG1003_09_PythonCoding
ENGG1003_09_PythonCoding
Python Coding
1
Control Flow
2
Revision
• Variables: count = 18; name = "Peter"; x = y =
2
• Expressions: count = count + 1; sum = x + y
• Conditions: x == y == 9; -5 < x <= y
• Branching: if x == y == 2: print(name, x, y)
else: print("x != 2 or y != 2")
• Repetition: for i in range(3, 9):
print( i, i * i )
x? 0 x? 41 x? -9
y? 0 y? 41 y? 41
z? 0 z? 5 z? 41
4
All are identical Not the same Not the same
Example Two: There are 3 mutually
exclusive cases.
Order 3 Tips for you…
• Create yet another New File order3.py print("Hi", 1, 3.14)
• Write some code to
x = float( input("x? ") )
• ask the user for 3 float numbers, x, y and z
y = float( input("y? ") )
• check if they are in certain order, e.g., x < y < z z = float( input("z? ") )
• print the message "Increasing order" or
"Decreasing order" or "Out of order" if x < y and y < z:
followed by the numbers x, y and z print("Increasing order", x, y, z)
elif x > y > z:
print("Decreasing order", x, y, z)
x? 1 x? -9 else:
y? 3 y? 41 print("Out of order", x, y, z)
z? 5 z? 41
Increasing order 1.0 3.0 5.0 Out of order -9.0 41.0 41.0
x? 9.8 x? 4.1
y? 0 y? 4.1
z? -2.718 z? 4.1 5
Decreasing order 9.8 0.0 -2.718 Out of order 4.1 4.1 4.1
Example Three: N = int( input("N? ") )
Multiples of 7 for i in range( 1, N+1 ) :
print( i * 7 )
• Create last New File multiple7.py
• Write some code to
• ask the user for ONE int (integer), N
• print the first N multiples of 7 using for i in range(…):
• Run, test and verify your work thoroughly and carefully:
N? 10
Assume user is cooperative that 7
N is always a positive integer 14
21
N? 1 28 N could be large,
7 35 thus leading to many
42 output lines!
N? 3 49
7 56
14 63
70 6
21
Outline – Python Coding
• Using libraries and packages
• Call functions
• Simple data types: list and tuple
• Text data type: string (str)
• Reading data table from the web in CSV
• Simple data processing and plotting
• Define functions
• Appendix - more data types: set and dictionary
7
Libraries/ Packages
• There are many Python programmers and projects
around the world.
11
Standing on Giant's
Shoulder!
• On the provided VM, commonly used libraries and packages are pre-
installed with Anaconda.
• A package may contain many modules; in turn many functions.
• We can import packages/ modules and give them a nickname:
fruits.append("Durian")
print(fruits)
15
Example Selecting Random
Frequencies for Signals testing:
shuffle a list
print("Random Frequencies for Experiments")
Start from 1; End before 100; Skip b
freqs = list( range(1, 100, 3) ) # create a new list
print("Original frequencies in ascending order:")
print(freqs)
import random
random.shuffle(freqs)
print("Shuffled frequencies (Ghz) in random order:")
print(freqs)
Random Frequencies for Experiments
Original frequencies in ascending order:
[1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97]
Shuffled frequencies (Ghz) in random order:
[97, 40, 28, 31, 52, 85, 82, 70, 64, 22, 1, 49, 73, 16, 34, 94, 25, 61, 58, 55, 37, 13, 43, 4, 19, 46, 76, 88, 7, 79, 67, 91, 10]
16
List Comprehension
• Syntax:
new_list = [ expression for member in iterable ]
Ref: https://www.w3schools.com/python/python_tuples.asp
19
Tuple Exercises
• Write some Python code to create a tuple named
part_dimension:
”Cylinder Block" 5.2 3.4 2.1
print("Volume",volume,"cubic units")
25
String
• Text information can be represented as string.
• Literal in a pair of 'single quotes' or "double quotes"
• For example:
cuhk = 'The Chinese University of Hong Kong'
sentence = "This is a GOOD day"
28
Iteration Using for
primes = [2, 3, 5, 7, 11, 13, 17, 19]
print(type(primes))
29
Define Functions
• We have been using existing modules and
functions.
30
Define and Use a Simple
Function
# define a function named sayHi Hi!
def sayHi(): Hi!
print("Hi!") Hi!
31
Function with a message
# define a function with parameter Hi! Peter
def greet(message:str): I'm happy!
print("Hi!", message) Hi! Mary
print("I'm happy!") I'm happy!
32
Function for Calculation
def inch2cm(inch:float):
return inch*2.54
1 inch = 2.54 cm
5 inches = 12.7 cm
3 feet = 0.9144 m
33
Function with Single Exit
# define a function with parameter
def daysInMonth(m:int):
if m == 2: days = 28
elif m in [4, 6, 9, 11]: days = 30
else: days = 31
return days
36
Summary
• Python provides list and tuple for structural data
storage and data processing
38
Set { , , , }
• Unordered, unindexed collection of unique items.
• Usage: membership management
• E.g., add/discard members, support set operations like difference,
union, intersection, subset/ superset/ membership checking, etc.
Ref: https://www.w3schools.com/python/python_sets.asp
39
Dictionary
{ key1:value1, k2:v2,
k3:v3, k4:v4 }
• A mapping of changeable key-value pairs.
• An item is referred to by using an unique key.
Ref: https://www.w3schools.com/python/python_dictionaries.asp
40
Dictionary
{ key1:value1, k2:v2,
k3:v3, k4:v4 }
majors = {"CSCI":"Computer Science", "INE":"Internet Engineering",
"CENG":"Computer Engineering"}
majors.update( {"AIST":"Artificial Intelligence Systems & Tech"} )
majors["INE"] = "Internet Engg"
print( majors["AIST"] )
print( majors.get("CENG") )
majors.pop("INE") # remove a particular key:value pair
del majors["INE"] # FAIL to remove "INE" again, KeyError
41
Dictionary Look-up
Example
dictionary = {"this":"pronoun", "is":"verb-to-be",
"a":"article", "good":"something pleasant", "day":"24 hours"}
sentence = "This is a GOOD day"
pieces = sentence.lower().split()
print("Broken into pieces:", pieces)
print("Dictionary look-up word by word:")
for word in pieces:
print("'", word, "' means", dictionary[word])