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

Mod 4 Python - Upd

Uploaded by

vanessagong2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Mod 4 Python - Upd

Uploaded by

vanessagong2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

ELEC3442 EMBEDDED SYSTEMS

Section 4: Python Language


PYTHON LANGUAGE
• High-level language, easy to use
• Do not need to explicitly declare data types
• No pointers
• Object-oriented programming, classes
• Slow compared to C, C++
• Interpreted, not compiled
• Hard to meet the real-time deadlines
• Two versions: Python 2.x and Python 3.x
• Python 2.x is still supported
• Programming differences are small
• Will use Python 3.x
ELEC3442 Embedded Systems 2
PYTHON 2 VS. PYTHON 3
• Print
• A statement in Python 2 but a function in Python 3
• Python 2: print “hello”
• Python 3: print(“hello”)
• In Python 3, prints each one, space separated
• print(“hello”,10) => hello 10
• Division
• Python 2 does exact integer division but Python 3 does true division
• Python 2: 1/2 => 0; 1.0/2 => 0.5
• Python 3: 1/2 => 0.5; 1//2 =>0

ELEC3442 Embedded Systems 3


PYTHON PROGRAMMING ENVIRONMENT

Two possible environments


• Integrated Development Environment (IDE)
• IDLE is the best option
• Invoke via Menu > Programming > Python
• Select Python 2 or Python 3 (use 3 for now)
• Text editor and interpreter separately
• Use Pico or Nano to write a program, says
“test.py”
• Execute program by typing “python3
test.py”
ELEC3442 Embedded Systems 4
EXECUTING PYTHON CODE

Two ways to do it
1. Interactive: execute lines typed interactively in a Python console
2. Batch: execute an entire Python program
• Interactive execution requires a Python shell
• Start IDLE, shell is default
• In terminal, type “python3” ELEC3442 Embedded Systems 5
EXECUTING PROGRAMS FROM IDLE

• Start IDLE
• File > New window to create
a new text editor window
• Type in code
• Select Run > Run Module
• Python shell will be opened
to execute the code

ELEC3442 Embedded Systems 6


TRY ON YOUR BROWSER

http://www.skulpt.org/

ELEC3442 Embedded Systems 7


INDENTATION
• Some languages use curly braces {} group lines of code together
• Python use indentation for nesting
>>> for i in range(2): >>> for i in range(2):
print(“a”) print(“a”)
print(“b”) print(“b”)

a a
b a
a b
b
ELEC3442 Embedded Systems 8
RANGE

• Produce a range of numbers


• E.g. range(4) gives 4 numbers, i.e., 0, 1, 2, 3

ELEC3442 Embedded Systems 9


COMMENTS

• Comments are for you to leave notes


• Ignored by the program
• # for single-line comment
• ””” (triple quotes) for multi-line comments

ELEC3442 Embedded Systems 10


ALGEBRAIC EXPRESSIONS
>>> 1+3
• Python shell can evaluate algebraic
4
expressions
>>> 10-3
• Many algebraic functions are
7
available
>>> (2+5)*7
• abs()
49
• min()
>>>3/2
• max()
1.5

ELEC3442 Embedded Systems 11


BOOLEAN EXPRESSIONS
>>> 2<5
• Evaluate to True or False True
• Often involve comparison >>> 4>9
operators False
<, >, ==, !=, <=, and >= >>> 1==3
False
>>> 1!=4
True
>>> 4<=4
True
>>> 5>=2
False ELEC3442 Embedded Systems 12
BOOLEAN OPERATORS
>>> 2<5 and 1<3
• Evaluate to True or False True
• May include Boolean operators >>> 4>9 and 2!=2
and, or, not False
>>> True and False
False
>>> True and True
True
>>> 4<=4 or 5>=2
True
>>> not (4>2)
False ELEC3442 Embedded Systems 13
VARIABLES AND ASSIGNMENTS

• Variable types are not declared >>> x = 2


>>> x
2
>>> 2*x
4
>>> y=3*x
>>> y
6

ELEC3442 Embedded Systems 14


STRINGS

• A sequence of characters enclosed in >>> ‘Hello World’


quotes ‘Hello World’
‘Hello World’ >>> a = ‘Good’
• Can be assigned to a variable >>> b = ‘Morning’
• Can be manipulated using string >>>
operators and functions

ELEC3442 Embedded Systems 15


STRING OPERATORS
Operator Definition >>> ‘Hello World’
‘Hello World’
x in s x is a substring of s
>>> a = ‘Good’
x not in s x is not a substring of s >>> b = ‘Morning’
a+b Concatenation of a and >>> a == ‘Good’
b True
a*n, n*a Concatenation of n >>> a != b
copies of a True
s[i] Character at index i of s >>>a < b
len(s) (function) length of True
string s >>> a> b
false ELEC3442 Embedded Systems 16
STRING OPERATOR EXAMPLES
>>> a = ‘Good’ >>>’x’ in b
>>> b = ‘Morning’ False
>>> a+b >>> len(b)
‘GoodMorning’ 7
>>> a+’ ’+b
‘Good Morning’
>>>3 * a
GoodGoodGood
>>> ‘o’ in a
True
ELEC3442 Embedded Systems 17
INDEXING OPERATOR

• Index of an item in a sequence is its >>> b = ‘Morning’


position in the sequence >>> b[0]
• Indexing operator is [], takes an index ‘M’
as argument >>> b[2]
• Indices start at 0 ‘r’
• Can be used to identify characters in a >>> b[6]
string ‘g’

ELEC3442 Embedded Systems 18


DEFINING FUNCTIONS
• A sequence of instructions associated
with a function name >>> def test():
• Function definition starts with def print(‘My first function’)
• Followed by function name,
open/close parentheses, and colon >>> test()
• All instructions in a function definition My first function
are indented
• IDLE does this automatically
• Function is called by typing function
name with parentheses after it
ELEC3442 Embedded Systems 19
FUNCTION RETURN VALUES
• Functions can return values with the
return instruction >>> def circle_area(rad):
• A function call is substituted for its return 3.14*rad*rad
return value in an expression
>>> circle_area(2)
12.56
>>> 2+circle_area(2)
14.56

ELEC3442 Embedded Systems 20


CLASS AND OBJECT
>>>class myClass:
• Object myVariable = “abc”
• Encapsulation of variables and def myFunction(self):
print(“I love python”)
functions into a single entity
• Class
• A template to create objects >>>myObject = myClass()
• Can create multiple objects from the >>>myObject.myVariable
same class ‘abc’
>>>myObject.myFunction()
I love python

ELEC3442 Embedded Systems 21


LISTS

• A comma-separated sequence of >>> pets = [‘ant’, ’bat’, ‘fish’,


items enclosed in square brackets ‘dog’]
• Items can be numbers, strings, other >>> lst = [0, 1, ‘two’, [3, ‘four’]]
lists, etc. >>> nums = [0, 1, 2, 4, 5, 6, 9]

ELEC3442 Embedded Systems 22


LIST OPERATORS AND FUNCTIONS
Operator Definition
x in lst x is an item of lst
x not in lst x is not an item of lst
lst1 + lst2 Concatenation of lst1 and lst2
lst*n, n*lst Concatenation of n copies of lst
lst[i] item at index i of lst
len(lst) Number of items in lst
min(lst) Minimum item in lst
max(lst) Maximum item in lst
sum(lst) Sum of items in lst
ELEC3442 Embedded Systems 23
LIST METHODS
• List operators that are called on the
list that they operate on
>>> lst = [1, 2, 3]
>>> lst.append(4)
[1, 2, 3, 4]

ELEC3442 Embedded Systems 24


LIST METHODS
Operator Definition
lst.append(item) Adds item to the end of lst
lst.count(item) Returns the number of items item occurs in lst
lst.index(item) Returns index of (first occurrence of) item in
lst
lst.pop() Removes and returns the last item in lst
lst.remove(item) Removes (the first occurrence of) item from
lst
lst.reverse() Reverses the order of items in lst
lst.sort() Sorts the items of lst in increasing order

• append(), remove(), reverse(), and sort() do not return valuesELEC3442 Embedded Systems 25
DICTIONARY
• Similar to array
• But work with keys and values instead of indices
• Each value stored in a dictionary is accessed by a key
>>>studentID = { >>>studentID = {
[“Peter”]: 112233, studentID[“Peter”] = 112233
[“Mary”]: 112256, studentID[“Mary”] = 112256
[“John”]: 115678 studentID[“John”] = 115678
} }

• Remove a value
>>>studentID.pop(“Peter”) >>>del studentID[“Peter”]
ELEC3442 Embedded Systems 26
CONTROL FLOW

• Statements that change the order in which lines of code are


execute:
• if statement if statement
• for loop If <condition>:
• while loop <indented code block>
<non-indented statement>

If temp>25:
print(‘It is hot!’)
print(‘Goodbye.’)
ELEC3442 Embedded Systems 27
IF-ELSE STATEMENT
if <condition>:
<indented code block 1>
else:
<indented code block 2>
<non-indented statement>

if temp>25:
print(‘It is hot!’)
else:
print(‘It is not hot!’)
print(‘Goodbye.’)
ELEC3442 Embedded Systems 28
FOR LOOP
• Executes a block of code for every element in a sequence

>>> name = ‘Ian’ >>> for name in [‘Peter’, ‘John’,


>>> for char in name: ‘Mary’]:
print(char) print(name)
I Peter
a John
n Mary
>>> >>>
• Any sequence can be used
• All code in loop must be indented ELEC3442 Embedded Systems 29
WHILE LOOP
• Execute indented block of code while condition is True

>>> i=0
>>> while i<3:
print(i)
i=i+1
0
1
2
>>>

ELEC3442 Embedded Systems 30


MODULE AND PACKAGE

• Module >>> import urllib


• Simple python file with the .py >>>dir(urllib)
extension ['__builtins__', '__cached__',
• Implement a set of functions '__doc__', '__file__', '__loader__',
• Use import to import a module '__name__', '__package__',
• Package '__path__',
• Contain multiple packages and '__spec__']
modules
• Simply directories
• Suppose a directory good which >>> import good.morning
contains a module morning ELEC3442 Embedded Systems 31
PYTHON VS C/C++ IN EMBEDDED SYSTEMS

- Adapted from [Src: https://opensource.com/life/16/8/python-vs-cc-embedded-systems]


v Undoubtedly, the C/C++ programming languages have dominated the embedded systems
programming or software for the past decades due to its low-level design (e.g. pointers to
directly access memories for driver programs) and faster computational speed for real-time
systems;
vYET Python has its high potential and strength for embedded system programming for the
following factors:
v Python is known for its writability, error reduction, and readability – w.r.t. C / C++;
v Python is the most popular introductory Prog. Lang. at the top CS dept. in US, i.e. increasing
popularity;
v Python is strongest as the communication middleman for which sending messages through
Python to or from an embedded system allows the user to easily automate testing;
v Embedded algorithms are getting increasingly complex. Python libraries like Theano or
TensorFlow that will optimize Python code for these processes, thus allowing ample
opportunities for integration - esp. thru the Edge AI;
v Development or runtime speed of Python is likely to be enhanced in the future due to its
popularity.
ELEC3442 Embedded Systems 32

You might also like