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

ENGG1003_09_PythonCoding

The document provides an overview of Python coding concepts, including control flow, variables, conditions, and functions. It includes examples of code for checking identical numbers, ordering floats, and calculating multiples of 7, along with explanations of lists, tuples, and their respective operations. Additionally, it discusses the use of libraries, versioning, and maintenance of Python environments.

Uploaded by

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

ENGG1003_09_PythonCoding

The document provides an overview of Python coding concepts, including control flow, variables, conditions, and functions. It includes examples of code for checking identical numbers, ordering floats, and calculating multiples of 7, along with explanations of lists, tuples, and their respective operations. Additionally, it discusses the use of libraries, versioning, and maintenance of Python environments.

Uploaded by

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

ENGG1003

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 )

• Python Basics Examples


3
Example One: BEWARE:
Assignment with =

Identical 3 Comparison with ==

Mind the colon and


• Create another New File identical3.py the 4 spaces!
• Write some code to x = int( input("x? ") )
• ask the user for 3 int (integers), x, y and z y = int( input("y? ") )
• check if they are all identical z = int( input("z? ") )
if x == y and y == z:
• print the message "All are identical" or
print("All are identical")
"Not the same" else:
print("Not the same")
x? 5 x? 5 x? 15
y? 5 y? 41 y? 24
z? 5 z? 5 z? -75
All are identical Not the same Not the same

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.

• People "open source" their work; or issue license.


• They are packaged and released as libraries.
• Such code can be re-used.

• We can install and manage libraries/ packages with


Anaconda, conda or pip.
8
Versioning and
Compatibility
• Hardware, software and tools are updated swiftly
• Tracked and recognized by version numbers, e.g., Python 3.12
• Different tools and packages are designed to work together,
based on known combinations and tested versions
• Mind you that some tools and packages are incompatible!
• Thus, there are dependencies and exclusions amongst the
tools
• Software and tools are installed/ updated at different times
on a working system
• Need to maintain a working set of tools properly
9
Different Ways of
Maintenance
• Maintain a single working environment using pip, the
package installer for Python
• pip, like IDLE, is bundled with Python installation
• But one size may not fit all
• Maintain multiple environments using Anaconda/
conda/ miniconda
• We may create, make changes, test and switch between
different environments
• We can install different versions of Python in different
environments, together with different tools
• We can just update some tools in one particular environment
10
Simplified Solution for You
• We have prepared a VM with Anaconda environments
• Software, tools and packages are properly installed
• All demonstrations and given code shall run properly
on the VM, under the provisioned environments
• Simple examples and exercises shall run properly on your
own computer, with standard Python setup
• In-depth examples and project work can be tried on the VM
• Enthusiastic students may try to setup tools and packages
on your own computer, using command like this:
pip install numpy scipy pandas scikit-learn matplotlib imutils

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:

import turtle as pet


pet.forward(100)

import random # import module random


cards = ["Spade King", "Heart Ace", "Diamond Queen",
"Club Jack"]
random.shuffle(cards)
from random import shuffle # import function shuffle
shuffle(cards)
12
List [ , , , ]
• List items are ordered, changeable, and duplicate values are allowed.
• Indexed: 1st item has index [0], 2nd item has index [1], etc.

equipment_list = ["Microscope", "Centrifuge", "Pipette", "Fume


Hood"]
print("First:", equipment_list[0]) # Microscope
equipment_list.append("Thermometer") # Append "Thermometer" at
the end
equipment_list[1] = "Spectrometer" # Replace "Centrifuge" with
"Spectrometer"
# the list becomes ['Microscope', 'Spectrometer', 'Pipette',
'Fume Hood', 'Thermometer']
for equipment in equipment_list:
print(equipment) # print list items, one on a line
del equipment_list[2] # Remove "Pipette"
print(equipment_list) # The list becomes ['Microscope',
'Spectrometer', 'Fume Hood', 'Thermometer']
Ref:
https://www.w3schools.com/python/python_li 13
List Exercises
• Write some Python code to create a list named
fruits:

"Apple" "Orange" "Banana"

• Append "Durian" to the existing list fruits:

"Apple" "Orange" "Banana" Durian

• Print the 3rd element using a proper index in fruits.


14
List Exercise Solution
fruits = ["Apple", "Orange", "Banana"]
print(fruits)

fruits.append("Durian")
print(fruits)

print("3rd:", fruits[2]) # third element

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 ]

where iterable could be another list, a range, etc.;


member, one at a time, can be used in expression
to generate a new list

>>> from math import sqrt


>>> roots = [ sqrt(i) for i in [4, 9, 16] ]
>>> roots
[2.0, 3.0, 4.0]
17
List Comprehension
• Syntax:
new_list = [ expression for member in iterable ]

where iterable could be another list, a range, etc.;


member, one at a time, can be used in expression
to generate a new list

>>> squares = [ i * i for i in range(10) ]


>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
18
Tuple ( , , , )
• Tuple items are ordered, unchangeable, and duplicate values are allowed.
• Indexed: 1st item has index [0], 2nd item has index [1], etc.
• E.g., a tuple can represent a record or some structural data

GPS_location_HK = (22.3700556, 114.1535941)


x_y_coordinates = (-3, 7)
student_record = (1154987651, "Peter PAN", "CSCI", 3.97)
print( GPS_location_HK )
print( student_record[2] )

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

Legend: Part Name, length, width and height

• Print the part name together with the width


• Calculate and print the volume in cubic units.
20
Tuple Exercise Solution
part_dimension = ("Cylinder Block", 5.2, 3.4, 2.1)
print(part_dimension)

print(part_dimension[0], ":", part_dimension[2], "units wide")

volume = part_dimension[1] * part_dimension[2] *


part_dimension[3]

print("Volume",volume,"cubic units")

('Cylinder Block', 5.2, 3.4, 2.1)


Cylinder Block : 3.4 units wide
Volume 37.128 cubic units 21
List and Tuple Exercises
• Write some Python code to create a list of tuples
named parts:
"Cylinder Block" 5.2 3.4 2.1

"Engine" 4.3 3.2 1.5

"Gearbox" 6.0 2.5 3.0

• Calculate and print the total volumes in cu


22
List and Tuple Exercise
Solution 1
parts = [
("Cylinder Block", 5.2, 3.4, 2.1),
("Engine Head", 4.3, 3.2, 1.5),
("Gearbox Casing", 6.0, 2.5, 3.0),
]
total_vol = parts[0][1] * parts[0][2] * parts[0][3] + \
parts[1][1] * parts[1][2] * parts[1][3] + \
parts[2][1] * parts[2][2] * parts[2][3]

print("Total Volume:", total_vol, "cubic units")


Total Volume: 102.768 cubic units 23
List and Tuple Exercise
Solution 2
parts = [
("Cylinder Block", 5.2, 3.4, 2.1),
("Engine Head", 4.3, 3.2, 1.5),
("Gearbox Casing", 6.0, 2.5, 3.0),
]
total_vol = 0
for i in range(len(parts)):
vol = parts[i][1] * parts[i][2] * parts[i][3]
total_vol += vol

print("Total Volume:", total_vol, "cubic units")


Total Volume: 102.768 cubic units 24
List VS Tuple
• [List] and (tuple) looks similar
• Both are ordered, indexed, allow duplicates
• List items can be changed; BUT NOT tuple items
fruits = [ "Apple", "Orange", "Banana" ]
fruits[0] = "Pear"
fruits[len(fruits) - 1] = "Strawberry"

things = ( "Tablet", "RAM", 256, "GB", 4, "cores" )


things[0] = "Notebook"
TypeError: 'tuple' object does not support item assignment

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"

• They can be joined together to form a longer string:


message = "I love " + cuhk + "!"
print(message)
I love The Chinese University of Hong Kong! 26
String Operations
sentence = "This is a GOOD day"
print("lower:", sentence.lower())
print("upper:", sentence.upper())
print("capitalize:", sentence.capitalize())
print("swapcase:", sentence.swapcase())
pieces = sentence.lower().split()
print("Broken into pieces:", pieces)
for word in pieces: lower: this is a good day
print( word ) upper: THIS IS A GOOD DAY
capitalize: This is a good day
swapcase: tHIS IS A good DAY
Broken into pieces: ['this', 'is', 'a', 'good', 27'day']
Iteration Using for
for i in range(1, 100):
print(i)

for i in ["pencil", "eraser", "compass"]:


print(i)

for i in ("HK", 3.14, 109700, ''):


print(i)

28
Iteration Using for
primes = [2, 3, 5, 7, 11, 13, 17, 19]

n = len( primes ) # find list length, 8

for index in range(n): # index from 0 to 7


print(index, ":", primes[index])

print(type(primes))

29
Define Functions
• We have been using existing modules and
functions.

• How to define our own functions?

• How to reuse some of our code?

30
Define and Use a Simple
Function
# define a function named sayHi Hi!
def sayHi(): Hi!
print("Hi!") Hi!

# call/ use the function


sayHi()
sayHi()
sayHi()

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!

# call the function with argument


greet("Peter")
greet("Mary")

32
Function for Calculation
def inch2cm(inch:float):
return inch*2.54

print("1 inch =", inch2cm(1), "cm")


print("5 inches =", inch2cm(5), "cm")
print("3 feet =", inch2cm(3*12)/100, "m")

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

# call the function with argument


print("Feb:", daysInMonth(2))
print("Nov:", daysInMonth(11))
print("Jul:", daysInMonth(7)) 34
Function with Multiple Exits
# define a function with parameter
def daysInMonth(m:int):
if m == 2: return 28
elif m in [4, 6, 9, 11]: return 30
else: return 31

# call the function with argument


print("Feb:", daysInMonth(2))
print("Nov:", daysInMonth(11))
print("Jul:", daysInMonth(7))
35
Return Multiple Values
from math import sqrt
# define a function that returns two values
def computeSquareAndSquareRoot(n:int):
return n**2, sqrt(n) # Return two values (separated by ,)

# call the function and store the two return values


# into "result1" and "result2"
result1, result2 = computeSquareAndSquareRoot(2)
print(result1) # Print 4
print(result2) # Print 1.4142135623730951

36
Summary
• Python provides list and tuple for structural data
storage and data processing

• Python string supports text processing

• Iteration using for

• Function definition and usage


37
Appendix
• More data types and data structures
• Set
• Dictionary

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.

members = { "Peter", "Mike", "Ann", "Bill" }


members.add( "Paul" )
members.discard( "Peter" )
print( members.issuperset( { "Mike", "Bill" } ) )
print( "Mike" in members )

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.

glossary = { "apple":"a red fruit", "car":"a vehicle" }


print( glossary["apple"] )
print( glossary["car"] )
print( glossary.keys( ) )
print( glossary.values( ) )

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

# use a tuple with a dictionary together


student_record = (1154987651, "Peter PAN", "CSCI", 3.97)
print( majors[ student_record[2] ] )

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])

Broken into pieces: ['this', 'is', 'a', 'good', 'day']


Dictionary look-up word by word:
' this ' means pronoun
' is ' means verb-to-be
' a ' means article
' good ' means something pleasant
' day ' means 24 hours 42

You might also like