Chapter 2 - Introduction To Python
Chapter 2 - Introduction To Python
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
[email protected] | [email protected]
Content
1. What is Python?
2. Preparation for Python
3. Python Programming Language
2
1. What is Python?
• Returning Output: checks the runtime error (if any), returns error
or exists with returned output.
Output
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
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))
• Input in Python
• Function input() gets a string from user.
>>> string = input(“Enter your string: “)
block of code
else: …
Code
block of code …
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')
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")
• 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
• 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
• 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()
• 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)
}
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 {.. : ..}
• 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
• 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()
44