0% found this document useful (0 votes)
41 views44 pages

Chapter 2 - Introduction To Python

python

Uploaded by

Duc Vuong Nguyen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
41 views44 pages

Chapter 2 - Introduction To Python

python

Uploaded by

Duc Vuong Nguyen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 44

EE3491 – KỸ THUẬT LẬP TRÌNH

PROGRAMMING TECHNIQUES

CHAPTER 2
Introduction to Python
Võ Duy Thành
Department of Automation Engineering
Control Technique and Innovation Lab. for Electric Vehicles
School of Electrical and Electronic Engineering
Hanoi University of Science and Technology
thanh.voduy@hust.edu.vn | thanh.voduy@ieee.org
Content

1. What is Python?
2. Preparation for Python
3. Python Programming Language

2
1. What is Python?

• Why Python? Looking back the top programming language


LabView 0.0091
Visual Basic 0.0326
Assembly 0.0383
Matlab 0.0502
PHP 0.1186
R 0.1316
HTML 0.139
TypeScript 0.1794
Go 0.2157
SQL 0.3397
C# 0.3973
JavaScript 0.4638
C 0.4641
C++ 0.538
Java 0.588
Python 1

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 3


1. What is Python?

• However, please NOTE that:


1. This course is NOT a programming language subject.
2. This course DOES NOT aim at teaching Python but uses Python
as a tool to quickly present the content, i.e., ideas or algorithms.
3. Instead of relying on Python libraries, students are required to
code from scratch and raw materials.
4. Students are recommended to redo the exercises in this course
with other programming languages.

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 4


1. What is Python? | 1.1. About Python

• Python is a high-level, general-purpose, and interpreted


programming language used in various sectors, including machine
learning, artificial intelligence, data analysis, web development, and
many more. Guido van Rossum, a
• Easy to use, read and understand Dutch programmer,
created Python in
• Powerful standard library late 1980s
• Dynamic semantics
• Object-oriented programming language
1991 • The first ever version
• Multi-platform
1994 • Version 1.0
• Free and open-source Demand for Python 1997 • Version 1.5
• Huge community developers has 2000 • Python 2.5
8.2/25 million increased by 41% in
Python the last 5 years 2008 • Python 3.0
developers 2023 • Version 3.12.0

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 5


1. What is Python? | 1.2. Python Interpreter – How it works

• Python needs an interpreter, CPython, written in C lang. Lexing


• Lexing: divide each line of code into a single action, called a
token, using lexer.
• Parsing: a parser checks the syntax error (if any) of tokens and Parsing
forms an Abstraction Syntax Tree (AST).
• Creation of byte code: a “compiler” converts AST into an
intermediate language code, called bytecode, and is stored in a Byte code
‘.pyc’ file creation
• Conversion to Machine-executable Code: Python Virtual
Machine (PVM) converts bytecode into machine code and
executes it. Conversion

• Returning Output: checks the runtime error (if any), returns error
or exists with returned output.
Output

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 6


2. Preparation for Python

• To work with Python, you need:


• Python interpreter: Python 3.12
(Windows Store), or download at:
https://www.python.org/downloads/
• Python text editor:
• Visual Studio Code (VS Code),
• Jupyter notebook,
• Spider …
• Python extension (if needed)
• Libraries: can be downloaded with
“pip” command
E.g.: pip download numpy

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 7


3. Python Programming Language | 3.1. Basic elements of Python

• A Python program (also called script) is a sequence of definitions and


commands
• Definitions and commands are executed in shell
• A command, also called a statement, instructs the interpreter to do
something
• Try the following statements then run:
print("I am a student") I am a student
print("I am studying at HUST") I am studying at HUST
print("I like rock and roll") I like rock and roll

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 8


3. Python Prog. Lang. | 3.2. Object, Expression, Numerical Types

• Objects are the core of Python


• Every object has a type that defines actions that the program can do
with that object
• Types can be scalar or non-scalar
• Scalar objects are indivisible
• Non-scalar objects have an internal structure
• Four types of scalar objects:
• int: integer numbers. Example: -5 or 106 or -10023
• float: real numbers, using decimal point. Example: 3.14159 or -100.8 or 1.6E3
• bool: Boolean values, including True or False.
• None: type with a single value.

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 9


3. Python Prog. Lang. | 3.2. Object, Expression, Numerical Types

• Try some commands in shell:


> python # this command will change to the python shell prompt
>>> 4+5
9
>>> 4.0 + 5.0
9.0
>>> 4.0 + 5 # explain what happen
????
>>> 3 != 2 # explain what happen
????
>>> 3 != 3 # explain what happen
????
>>> (Ctrl+z to come back to the interactive window)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 10


3. Python Prog. Lang. | 3.2. Object, Expression, Numerical Types

• Operators on objects of scalar types


i + j is the sum of i and j
i – j is i minus j
i * j is the product of i and j
i / j is i divided by j
i // j is the integer division
i % j is the remainder of the division
i ** j is i raised to the power of j
The comparison operators:
== (equal), != (not equal),
> (greater), < (less),
>= (at least), <= (at most)
The primitive operators for Boolean type:
and, or, not
Try them yourself with the shell prompt

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 11


3. Python Prog. Lang. | 3.2. Object, Expression, Numerical Types
pi = 3
• Variables and Assignment radius = 11
• Variables provide a way to area = pi * (radius ** 2)
associate (bind) names with radius = 20
objects
• In Python, a variable is just a name pi pi
• So, choose appropriate names for 3 3
easy understanding, debugging radius 11 radius
• Do not use Python keywords to area 363 area 363
name a variable
20
• Add comments as much as
possible, using # symbol

Python keywords: and, as, assert, break, class, continue, def, del, elif, else,
except, False, finally, for, from, global, if, import, in, is, lambda, nonlocal, None,
not, or, pass, raise, return, True, try, while, with, yield
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 12
3. Python Prog. Lang. | 3.2. Object, Expression, Numerical Types

• Practice in text editor: type, guess and run

my_message = "Hello World!"


print("My message: ", my_message)
my_number = 12345
print(my_number)
print(my_message,my_number)
print("I want to break the line here \n to get a new line")

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 13


3. Python Prog. Lang. | 3.2. Object, Expression, Numerical Types

• Practice in text editor: type, guess and run


a = 6 # integer
b = 5.0 # float
a, b = 6, 5.0 # This definition is also legal

print(a, b)
print(a + 4, b + 2) # guess what will be printed? Any comment?
print(a + 4.0, b + 2)
print(a / 2, a * 4)

# Sometimes we may want to change the data type of a variable -> use casting
a = float(a) # a is now a float variable
b = int(b) # b is now an integer number
print(a,b)
print("Data type of a is: ",type(a), ", and Data type of b is: ", type(b))

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 14


3. Python Prog. Lang. | 3.3. Strings and Input

• Objects of type str are used to represent strings of characters


• Can use either single/double quotes, e.g. ‘abc’ or “abc”
• The literal ‘123’ denotes a string of 3 characters, not a number
• Try following commands in shell prompt and explain the result
>>> ‘a’
>>> 3*4
>>> 3*’a’
>>> 3+4
>>> a
>>> ‘a’+’a’
>>> ‘a’*’a’

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 15


3. Python Prog. Lang. | 3.3. Strings and Input

• Some operation/function with string:


• len() returns the length of the string
>>> len(‘abc’) returns 3
• Indexing is used to extract a character at the position of the index. Note:
Python indexes from Zero. Indices can be a negative number
>>> ‘abc’[0] returns ‘a’ and ‘abc’[3] returns an error
>>> ‘abc’[-1] returns ‘c’ and ‘abc’[-3] returns ‘a’
• Slicing is used to extract a sub-string with arbitrary length
• Syntax: str[start:end] or str[start:end:step]
• First index: start and last index: end-1
>>> ‘I am studying at HUST’[2:6] returns ‘am s’
a b c d e f
I a m s t u d … 0 1 2 3 4 5
0 1 2 3 4 5 6 7 8 … -6 -5 -4 -3 -2 -1

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 16


3. Python Prog. Lang. | 3.3. Strings and Input

• Some built-in functions with string


• Upper case: str.upper()
• Lower case: str.lower()
• Remove whitespace: str.strip()
• Replace string: str.replace()
• Split string: str.split()
• String format: str.format()

Find more information:


https://www.w3schools.com/python/python_strings.asp
https://www.geeksforgeeks.org/python-string/
https://docs.python.org/3/library/string.html

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 17


3. Python Prog. Lang. | 3.3. Strings and Input

• Practice in text editor: type, guess and run


a = True
b = False
HUST_men = "Handsome"
print("Are HUST men handsome? ",bool(HUST_men)) # True or False?
NEU_men = "Rich"
print("Are NEU men as rich as HUST men? ",bool(NEU_men == HUST_men))

my_str = "This is my string variable"


print(my_str)
print(my_str[1]) # guess what will be printed?
print(my_str[5:13])

added_str = "And added string"


print(my_str + ". " + added_str + ".")
new_str = my_str[2:5] + my_str[8:15]
print(new_str) # guess what will be printed? Comment on the last index
new_str = my_str[:]
print(new_str) # Comment on ':' operand

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 18


3. Python Prog. Lang. | 3.3. Strings and Input

• Practice in text editor: type, guess and run


# Example for String format
Quantity = 3
Item_no = 567
Price = 49.95
My_order = "I want {} pieces of item {} for {} dollars."
print(My_order.format(Quantity, Item_no, Price))
print(My_order)

My_Univ = “I am studying in HUST” # Guess what will be printed


print(My_Univ[::-1])

Try other functions with string yourself!

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 19


3. Python Prog. Lang. | 3.3. Strings and Input

• Input in Python
• Function input() gets a string from user.
>>> string = input(“Enter your string: “)

• Want to get numerical from user? Use type conversion (casting)


>>> int_number = int(input(“Enter your integer number: “))
>>> float_number = float(input(“Enter your float number: “))

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 20


3. Python Prog. Lang. | 3.3. Strings and Input

• Practice in text editor: type, guess and run

my_str = input("Input gives you a string: ")


my_num_int = int(input("Type an int number: "))
my_num_float = float(input("Type a float number: "))
print(my_str, my_num_int, my_num_float)
print(5*my_str, 6*my_num_int, 7*my_num_float) # guess what will be printed

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 21


3. Python Prog. Lang. | 3.4. Branching programs

• The simplest branching statement is the conditional


statement. Note: Python uses indentation.
• Step 1: Check the condition if it is True or False
• Step 2: Execute a code block if the condition is True …
• Step 3: Execute another code block if False (optional) Code

if Boolean expression: True False


Test
block of code
or True False
if Boolean expression: block block

block of code
else: …
Code
block of code …

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 22


3. Python Prog. Lang. | 3.4. Branching programs

• Practice in text editor: type, guess and run


x = int(input('Enter a number:'))
if x%2 == 0:
print('Even')
else:
print('Odd')
print('Done with conditional’)

if x%2 == 0:
if x%3 == 0:
print('Divisible by 2 and 3’)
else:
print('Divisible by 2 and not by 3')
elif x%3 == 0:
print('Divisible by 3 and not by 2')

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 23


3. Python Prog. Lang. | 3.4. Branching programs

The flexibility of Python:


String = input("Enter your string: ")
if 'a' in String:
print('There is charater a in the string')
else:
print('No a in the string')
Finger exercise:
1. Write a program to implement the division of two numbers entered by
the user with divide-by-zero checking.
2. Write a program that examines three variables: x, y, and z, and prints
the largest odd number among them. If none of them are odd, it should
print a message to that effect.

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 24


3. Python Prog. Lang. | 3.5. Iteration

• Iteration is the way of repeating operations, called loop


• Step 1: test the condition …
Code
• Step 2: execute the code block if the condition is true …
• Step 3: jump back step 1
Loop
• Two popular iteration statements: Test
• For-loop This is the condition.
for counter in range(): counter increases each loop True False

block of code Code


Loop until condition is False. block
• While-loop Use break to break the loop
while condition: …
block of code Code

• Remember to use indentation

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 25


3. Python Prog. Lang. | 3.5. Iteration

• Practice in text editor: type, guess and run


Compare the two codes:

My_str = "Hanoi is the Capital of Vietnam" My_str = "I am a student of HUST"


for i in range(len(My_str)): i = 0
if My_str[i] == "a": while i <= len(My_str):
print("There is \'a\' in the string") if My_str[i] == "a":
print("There is \'a\' in the string")
break
i += 1

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 26


3. Python Prog. Lang. | 3.5. Iteration

• Practice in text editor: type, guess and run

import random
number = 0
counter = 0 Before using special functions,
while True : we need to import libraries
number = random.random() There are lots of libraries in Python
counter += 1
if number > 0.8 :
break
print("The random value is:", number, "after", counter, "loops")

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 27


3. Python Prog. Lang. | 3.5. Iteration

• Practice in text editor: type, guess and run


Some uses of For-loop
for x in range(6):
print(x)
for x in range(2, 6):
print(x)
for x in range(2, 30, 3):
print(x)
Compare two codes of for-else:
for x in range(6): for x in range(6):
print(x) if x == 3: break
else: print(x)
print("Finally finished!") else:
print("Finally finished!")

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 28


3. Python Prog. Lang. | 3.6. More variable types

• Python List
• Used to store multiple (collection) items in a single variable
• List variable is created using square brackets
My_list1 = [“pen”, “book”, “calculator”, “recorder”]
• List items are allowed duplicate value, i.e., items with the same value
My_list2 = [“pen”, “book”, “pen”, “recorder”]
• List items are indexed
• List items are changeable: change/add/remove items in the list
• List items are ordered: order of items will not change. Once an item is added, it
is placed at the end of the list
Example: My_list3 = [“apple”, “banana”, “cherry”]
My_list4 = [1, 4, 5, 2, 25, 80, 5]
My_list5 = [True, False, True]
My_list6 = [“HUST”, 5, True, 60, “Student”]
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 29
3. Python Prog. Lang. | 3.6. More variable types

• Operations on Python List


• Access list items: by index,
My_list1[2], My_list1[2:10], My_list1[-4:-1]
• Change list items
My_list3 = [“apple”, “banana”, “cherry”]
My_list3[1] = “chili”
My_list3[1:3] = “berry” #set the first and second items same value
• Insert items
My_list3.insert(1,”watermelon”) There are various functions (methods)
• Add list items (to the end of the list) for List type (and other types as well).
My_list3.append(”durian”) Please surf the document before
thinking of manipulating them
• Remove list items
My_list3.remove(“banana”)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 30


3. Python Prog. Lang. | 3.6. More variable types

• Python Tuples
• Tuples are used to store multiple items in a single variable.
• Tuple variable is created using round brackets
My_tuple1 = (“pen”, “book”, “calculator”, “recorder”)
My_tuple2 = (“pen”,) # Tuple with one item. Note the comma
• Tuples are allowed duplicate value, i.e., items with the same value
My_tuple3 = (“pen”, “book”, “pen”, “recorder”)
• Tuple items are indexed
• Tuple items are unchangeable: unable to change/add/remove items
• Tuple items are ordered: order of items will not change.
Example: My_tuple4 = (“apple”, “banana”, “cherry”)
My_tuple5 = (1, 4, 5, 2, 25, 80, 5)
My_tuple6 = (True, False, True)
My_tuple7 = (“HUST”, 5, True, 60, “Student”)
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 31
3. Python Prog. Lang. | 3.6. More variable types

• Operations on Python Tuples


• Access tuple items: by index
My_tuple1[2], My_tuple1[2:5], My_tuple1[-2:-1]
• Update/change tuple items: Although Tuples are unchangeable, we can
workaround by casting to List type
My_tuple4 = (“apple”, “banana”, “cherry”)
temp_list = list(My_tuple4)
temp_list[2] = “kiwi”
My_tuple4 = tuple(temp_list)
• By casting a Tuple to a List, we can use methods of List type.

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 32


3. Python Prog. Lang. | 3.6. More variable types

• Python Sets
• Sets are used to store multiple items in a single variable.
• Set variable is created using curly brackets
My_set1= {“pen”, “book”, “calculator”, “recorder”}
• Duplicates Not Allowed
• Sets are unordered
• Set items are unchangeable. Once it is created, items can not be changed.
• Cannot access set items by index, but can loop through the set
• Add set item by add() function
• Can join two sets by union()

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 33


3. Python Prog. Lang. | 3.6. More variable types

• Python Dictionaries
• Dictionaries are used to store data value in key:value pairs
• Dictionary variables are ordered, changeable, and do not allow duplicates
• Dictionary items can be accessed by key
• Change a value by assigning a new value for an available key
• Add item by using a new index key and its value
my_dict = { my_dict[“power”] = 70
"brand": "Vinfast", for x in my_dict:
"type": "Electric", print(x)
"model": "VF9", print(my_dict[x])
"year": 2023, for x in my_dict.value()
"color": ["red", "black", "blue"] print(x)
}

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 34


3. Python Prog. Lang. | 3.6. More variable types

List Tuple Set Dictionary

Store multiple data Store multiple data Store multiple data Store data in
in a single variable in a single variable in a single variable key:value pairs

Created with […] Created with (…) Created with {…} Created with {.. : ..}

Allow duplicate Allow duplicate No duplicate No duplicate

Ordered Ordered Unordered Ordered

Changeable Unchangeable Unchangeable Changeable

Access by index Access by index Cannot access item Access by key

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 35


3. Python Prog. Lang. | 3.7. Output with Plot

• Plot is a type of visual illustration, much like Matlab plot


• The most popular library: matplotlib
import matplotlib
(install matplotlib library: > pip install matplotlib)
• Submodule pyplot contains most of matplotlib utilities. Pyplot is
normally imported under plt alias
import matplotlib.pyplot as plt
• From now on, the pyplot package can be referred to as plt
• Popular plot styles: trend, scatter, bars, histograms, pie chart

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 36


3. Python Prog. Lang. | 3.7. Output with Plot

• Practice in text editor: type, guess and run


import matplotlib.pyplot as plt
xpoints = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ypoints = [3, 10, 8, 9, 4, 5, 2, 5, 7]
plt.plot(xpoints, ypoints)
plt.xlabel(“X points”)
plt.ylabel(“Y points”)
plt.grid()
plt.show()

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 37


3. Python Prog. Lang. | 3.7. Output with Plot

• Finger exercise: Plot two periods of a sinusoidal signal


(frequency/amplitude do not matter)
import matplotlib.pyplot as plt
import math
sin_data = []
theta = []
for i in range(720):
sin_data.append(math.sin(math.radians(i)))
theta.append(i)
plt.plot(theta, sin_data)
plt.xlabel("Angle [degree]")
plt.ylabel("Sinusoidal amplitude")
plt.grid()
plt.show()

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 38


3. Python Prog. Lang. | 3.8. Functions in Python

• Functions are blocks of code that can be used frequently


• Python built-in functions in libraries, e.g. sin(), cos(), append()…
• Creating and calling user-defined functions:
def function_name(parameters) | function_name(parameters)

import math a = int(input("Enter first parameter: "))


def delta_cal(a, b, c): b = int(input("Enter second parameter: "))
delta = b**2 - 4*a*c c = int(input("Enter third parameter: "))
if delta >= 0: delta = delta_cal(a,b,c)
return delta if delta == False:
else: print("The equation has no root")
return False else:
print("First root is: ", (-b+math.sqrt(delta))/(2*a))
print("Second root is: ", (-b-math.sqrt(delta))/(2*a))

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 39


3. Python Prog. Lang. | 3.8. Functions in Python

• Function with arbitrary parameters/arguments


• If we do not know how many arguments that will be passed into the function
→ add ‘*’ before the parameter name in the function definition
→ The function will receive a tuple of arguments → access the items
def car_collection(*car):
print("Brand name:", car[0])
print("The latest commercial car is: ", car[len(car)-1])
car_collection("Ford", "Ranger", "Raptor")
• Keyword arguments (note: the order of the arguments)
def my_children(child3, child2, child1):
print("The youngest child is " + child3)
my_children(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 40


3. Python Prog. Lang. | 3.8. Functions in Python

• Finger exercise:
1. Write a function that returns the larger number of the two input numbers
2. Ceasar Cipher is a simple encryption technique. It replaces letters in a word by
letters from some fixed number of positions down the alphabet. E.g. the
encrypted word “hanoi” is “jcqpk” if the shift position is 2. Here is the code:
alphabet = "abcdefghijklmnopqrstuvwxyz"
def cipher(word, shift):
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
new_word = ""
for letter in word:
letter_index = alphabet.index(letter)
new_letter = shifted_alphabet[letter_index]
new_word += new_letter
return new_word
Write a function to decrypt the word that is encrypted by Ceasar Cipher,
given the shift position.
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 41
3. Python Prog. Lang. | 3.9. Scoping

• Scope is mapping of names to objects (variables/functions)


Global scope f(x) scope
def f(x):
y = 1 f(x) Some codes y 1
x = x + y x 3 x 4
print('x=', x)
return x y 2
x = 4
x = 3 z f(x)
y = 2
z = f(x) Result:
print('z=',z) z = 4 x = 4
print('x=',x) x = 3 z = 4
print('y=',y) x = 3
y = 2 y = 2

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 42


3. Python Prog. Lang. | 3.9. Scoping

• What happens with this code? Draw the scopes yourself and explain.
def f(x):
def g():
x = 'abc'
print('x =', x)
def h(): Result:
z = x x = 4
print('z =', z) z = 4
x = x + 1 x = abc
print('x =', x) x = 4
h() x = 3
g() z = <function f.<locals>.g at 0x00000138BB2EE700>
print('x =', x) x = abc
return g
x = 3
z = f(x)
print('x =', x)
print('z =', z)
z()

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 43


End of
Chapter 2

44

You might also like