Python and Coding Basic
Python x IoT
0. Run our first python code
Open VS code
• Search and open “Visual Studio Code”
• VS code is a coding editor
• Designed to help with coding
Other editor example:
• Sublime Text
• Visual Studio Code
•…
Install Python Extension in VS Code
• Open VS Code
• Click on the extension icon on
sidebar
Install the Python extension
Enter python in the
search box at the top of
the Extensions view.
In the main area, where you see the details about the
Python extension, select Install.
Open a project folder
1. Open the top menu bar
2. Select “Open Folder”
3. Create a new folder “Python x AI” in
Documents
4. Click Open
File Explorer
Editor
Create a new python file
1. Right Click on the explorer
2. Select “New File”
3. Name it [Link]
Hello world!
1. Double Click on “[Link]”
2. Enter “print(‘hello! Your name’)”
3. Click on Play button and check the result in terminal
1. Python basic
What is function? (e.g. print( ))
Syntax that can carrout certain action,functions include:
- function name:print ()
- function variable: ()
- data processed by the function:"Hello World!"
print('Hello world')
input function output
Keywords
Each keyword is like the name of functions and variables,
each of them are case sensitive and users need to enter the
exact same name in order to call the specific function or
variable
Code:
print(‘Una’) # print() function will print out the data passed in the function
Output:
"Una"
Variables
1 mystring
Define variables:
var1 = 1 var1 var2
var2 = 'mystring'
Access variables: 1*3=3
result = var1*3
result
var1
Data type
• Dynamic type (Determine the data type during runtime)
Type Ordered Mutable Example
int / / 5
float / / 6.523
string Yes No “Hello everyone!”
bool / / True, False
list Yes Yes [1, 2, “abc”, 3]
dictionary No Key: No {“name”: “peter”,
“age”:5}
Operator
• Perform specific mathematical, relational or logical operation and
produce the final result.
Mathematical Operator Relational Operator Logical Operator
Operator Function Operator Function Operator Function
+ Addition == Equal to and True when both
- Subtraction != Not equal to sides are true
* Multiplication > Larger than or True when one
sides are true
/ Division >= Larger than or
equal to not Changes true to
** Exponentiation false, and false
% Modulo < Less than to true.
// Integer division <= Less than or
equal to
Conditional statement
Syntax: True False
Condition 1
if Condition 1:
Code A
True False
Code A Condition 2
elif Condition 2:
Code B
Code B Code C
else:
Code C
Example:
Code: Output:
a = 100 a is greater than b
b = 50
if b > a:
print('b is greater than a')
elif a == b:
print('a and b are equal')
else:
print('a is greater than b')
List
Syntax of list:
0 1 2 3 4 List symbol
fruits = [' ' Apple ', ' Orange ', ' Banana ', ' Grape ', ' Durian ' ]
Separator
Name of the list Elements in the list
fruits[0] -> 'Apple'
fruits[3] -> 'Grape'
Acces the list
Access single element of the list:
fruits[2]
Iterate list element by for loop:
# find index of orange
count = 0
for item in fruits:
if item == 'Orange':
print(f'The index of orange is {count}')
count += 1
Loop statement – For Loop
Syntax:
for element in list:
Code True
Condition 1
False
while Condition:
Code
Code
break # terminate the loop
continue # skip 1 iteration of loop
Example:
Code: Output:
color = ["red", "green", "blue"] red
for x in color: green
print(x) blue
for x in range(4): 0
print(x) 1
2
3
i = 1
while i < 4: 1
print(i) 2
i += 1 3
Function
Create function syntax: Input
def my_function(input1):
Code my_function Function code
return output
Call function syntax: Output
my_function(x)
Example:
Code: Output:
def my_function(x): 4
if(x < 3):
result = x - 1
else:
result = x + 1
return result
print(my_function(3))
Classes/Objects
• Almost everything in Python is an object, with its properties and methods.
• A Class is like an object constructor, or a "blueprint" for creating objects.
Create class syntax: Create object syntax:
class Human: may = Human('May', 17)
def __init__(self, name, age) Get properties in object:
[Link] = name [Link]
[Link] = age Call method in object:
def dance(self, dance_type) [Link]('jazz')
code…
Example:
Code: Output:
class Animal: Duffy
def __init__(self, name, age): 5
[Link] = name I am Duffy
bibibibibibibi~~~
[Link] = age
def sing(self):
print('I am', [Link])
print('bibibibibibibi~~~')
m1 = Animal('Duffy', 5)
print([Link])
print([Link])
[Link]()
Python Library
• You can install libraries by pip and use import statement for using
them.
Import library into your program:
import math
import math as m
Use imported library:
[Link](10.23) 11
[Link](5.23) 5
Example:
Code: Output:
import math 8.0
import datetime 2021-07-06 08:15:49.248310
x = [Link](64)
print(x)
y = [Link]()
print(y)
2. Coding Style
Good coding habits
• Use Descriptive Naming Conventions
Ø Variables, functions, and classes should be named in a way that they describe what
they do.
Ø Variable and function names are usually in snake_case (e.g. error_check)
Ø Constant variable names are usually in all Upper case (e.g. SCERET_CODE)
Ø Class names are in CamelCase (e.g. LightSensor)
• Abstract your Code using functions
Ø Functions hide the details of their operation, allowing you to think at a higher level
of abstraction. You don't need to know how a function works to use it - you just need
to know what it does.
• Always leave comments
3. Exercise
Please download [Link]
from shared folder
Mastermind (Number)
• Please download [Link]
from shared folder
• Drag the file input VS code explorer
• Finish 5 tasks which is in “…”
1 – Get input from user
• Syntax to get input
my_number = input('Input your number’)
• The value retrieved from the input function must be a string
• Please use the syntax above to finish task 1
2 – Check number and digit
• Syntax to check string is a number
[Link]()
• Syntax to get the length of a string
len(test)
• Please use “and” to combine two condition
3 - Determine if the number is in the correct position
Syntax:
a = [1,2,3,4]
b = [3,2,4,1]
for i in range(4):
Code
i in the number of completions of the loop
- In this loop, I would be 0, 1, 2, 3
- This concept is usually used to compare/combine/update the value
of multiple lists
- e.g. a[i] == b[i]
4 - Determine if the number is in the list
• Syntax to check if the number is in the list
my_list = [1,2,3,4]
b = 3
if b in my_list:
print(‘Exist’)
5 – What is the result of variable?
Hints:
• = symbol is an assign operater
• a = 3 means assign 3 in to variable a
• To increment the value of the variable, we can use the variable after =
e.g. a = a + 3
• In Python, if we add two strings using the '+' operator, the interpreter
will join/concatenate the two strings together.
E.g., if a = “hello ” + “world”
The value of a will be “hello world”
4. Familiar with List and Dictionary
38
List
Syntax of list:
0 1 2 3 4 List symbol
fruits = [' ' Apple ', ' Orange ', ' Banana ', ' Grape ', ' Durian ' ]
Separator
Name of the list Elements in the list
fruits[0] -> 'Apple'
fruits[3] -> 'Grape'
Acces the list
Access single element of the list:
fruits[2]
Iterate list element by for loop:
# find index of orange
count = 0
for item in fruits:
if item == 'Orange':
print(f'The index of orange is {count}')
count += 1
Dictionary
We can use dictionary to store data systematically by giving the values a key
as an identifier
fruit_storage = { Dictionary symbol
Key 'apple' : 3, Element Separator
'orange': 4,
Apple Orange Banana
'banana': 7 Value
} Key-Value Separator
Use square brackets
Get value by key from dictionary:
orange_storage = fruit_storage['orange']
Name of Key
dictionary
Real-life data: Combined List and dictionary
Observatory Website:
[Link]
ype=rhrread&lang=en
1. Open the link, copy all of the text
2. Create [Link] in folder explorer
3. Paste the text into [Link]
4. Right click and choose Format Document
5. Save the file
42
Read json file in python
• Create a file with name [Link]
• Use the code below to read [Link] file
import json
with open('[Link]', 'r') as json_file:
weather = [Link](json_file)
print(weather)
43
Structure of real-life dictionary
The curly bracket means it is a dictionary.
And we need to use Key to access temperature data
E.g.
print(weather['temperature'])
Structure of real-life dictionary
The curly bracket means it is a dictionary.
And we need to use Key to access data detail
E.g.
print(weather['temperature']['data'])
Structure of real-life dictionary
The square bracket means it is a list.
And we need to use index to access element
(We can also use for loop to iterate the list to check all
of the element)
E.g.
print(weather['temperature']['data'][0])
Structure of real-life dictionary
The curly bracket means it is a dictionary.
And we need to use Key to access the element detail
E.g.
print(weather['temperature']['data'][0] ['value'])
Exercise:
• Find the current humidity
• Find the current temperature at Sha Tin
Ø Try to use for loop to check the location instead of using the index number to
access the list
Ø For example, create a variable “location”, then the program will print the
temperature of the location
location = 'Sha Tin'
# Your code below
…
48
Appendix: Install VS Code and
Python
Download Visual Studio Code
• Download Visual Studio Code from Official Website
• Link: [Link]
Unzip and install software
1. Go to Download folder
2. Double click on the zip file
• Drag the Visual Studio Code app to Application
Download Python installation file
• Link: [Link]
• Mouse over on Downloads and click on Python 3.10.3
2
Install Python
1. Go to Download folder
2. Double click on the installation file
3. Press “Continue” and “Agree” to complete the installation process