You are on page 1of 12

Contents Python Getting Started

Python Tutorial BASIC ................................. 1 #!/bin/python3


print("Hello, World!")
Python Getting Started .............................. 1
Python Syntax
Python Syntax ........................................... 1 if 5 > 2:
Python Comments ..................................... 1 print("Five is greater than two!")
if 5 > 2:
Python - Variable Exercises ...................... 1 print("Five is greater than two!")
x=5
Python Data Types .................................... 1 y = "Hello, World!"
Python Numbers ........................................ 2 print(x)
print(y)
Python Casting .......................................... 2 #Five is greater than two!
#Five is greater than two!
Python Strings ........................................... 2 #5
#Hello, World!
Python Booleans ....................................... 4
Python Lists .............................................. 4 Python Comments
#This is a comment.
Python Tuples ........................................... 6 print("Hello, World!")
"""
Python Sets ............................................... 7 This is a comment
Python Dictionaries ................................... 9 written in
more than just one line
Python - Nested Dictionaries : từ điển lồng """
................................................................ 10 print("Hello, World!")
Hello, World!
Python If ... Else ...................................... 11 Hello, World!
Python While Loops ................................ 11 Python - Variable Exercises
Python For Loops .................................... 11 x = str(3) # x will be '3'
y = int(3) # y will be 3
Python Functions..................................... 11 z = float(3) # z will be 3.0
print(x,y,z)
Python Lambda (ẩn danh) ....................... 12 x = 5
y = "John"
Python Arrays ......................................... 12 print(type(x),type(y))
x, y, z = "Orange", "Banana", "Cherry"
print(x,y,z)
..Thuật toán x = "awesome"
Python print("Python is " + x)
Framework 3 3 3.0
Machine learning <class 'int'> <class 'str'>
Deep learning Orange Banana Cherry
Mấy cái sota Python is awesome
Linear algebra
Statistic & probability
1 Pytorch, sklearn, caffe, tensorflow, keras Python Data Types
Text Type: str
Python Tutorial BASIC Numeric Types: int, float, complex

Huy init | https://www.facebook.com/huyinit13


consectetur adipiscing elit,
Sequence Types: list, tuple, range
sed do eiusmod tempor incididunt
Mapping Type: dict ut labore et dolore magna aliqua."""
print(a)
Set Types: set, frozenset if "Lorem" in a:
print("Yes, 'free' is present.")
Boolean Type: bool Hello
5
Binary Types: bytes, bytearray, memoryview e
x = ["apple", "banana", "cherry"] banana
#display x: Lorem ipsum dolor sit amet,
print(x) consectetur adipiscing elit,
#display the data type of x: sed do eiusmod tempor incididunt
print(type(x)) ut labore et dolore magna aliqua.
['apple', 'banana', 'cherry'] Yes, 'free' is present.
<class 'list'>
Slicing Strings
Python Numbers b = "Hello, World!"
#convert from int to float: print(b[2:5])
x = float(1) print(b[:5])
#convert from float to int: print(b[2:])
y = int(2.8) print(b[-5:-2])
#convert from int to complex: llo
z = complex(x) Hello
print(x,y,z) llo, World!
print(type(x),type(y),type(z)) orl
1.0 2 (1+0j)
<class 'float'> <class 'int'> <class 'complex'>
Python - Modify Strings
a = " Hello, World! "
Python Casting print(a.upper())
x = int(1) print(a.lower())
y = int(2.8) print(a.strip()) #Remove Whitespace
z = int("3") print(a.split(","))
print(x,y,z) HELLO, WORLD!
x = str("s1") hello, world!
y = str(2) Hello, World!
z = str(3.0) [' Hello', ' World! ']
print(x,y,z)
123 txt = "Hello my friends"
s1 2 3.0 txt.upper()
print(txt)
Python Strings txt=txt.upper()
Basic: print(txt)
a = "Hello" Hello my friends
print(a) HELLO MY FRIENDS
print(len(a))
2 print(a[1])
for x in "banana": String Format
print(x,end=' ')
print() age = 36
a = """Lorem ipsum dolor sit amet, txt = "My name is John, and I am {}"

Huy init | https://www.facebook.com/huyinit13


print(txt.format(age))
string are alphanumeric
quantity = 3
itemno = 567 isalpha() Returns True if all characters in the
price = 49.95 string are in the alphabet
myorder = "I want {} pieces of item {} for {}
dollars." isdecimal() Returns True if all characters in the
print(myorder.format(quantity, itemno, price)) string are decimals
myorder = "I want to pay {2} dollars for {0} pieces of
item {1}." isdigit() Returns True if all characters in the
print(myorder.format(quantity, itemno, price)) string are digits
My name is John, and I am 36
I want 3 pieces of item 567 for 49.95 dollars. isidentifier() Returns True if the string is an
I want to pay 49.95 dollars for 3 pieces of item 567. identifier

islower() Returns True if all characters in the


String Methods string are lower case
Python has a set of built-in methods that you can use
on strings. isnumeric() Returns True if all characters in the
Note: All string methods returns new values. They do string are numeric
not change the original string.
isprintable() Returns True if all characters in the
Method Description string are printable

capitalize() Converts the first character to upper isspace() Returns True if all characters in the
case string are whitespaces

casefold() Converts string into lower case istitle() Returns True if the string follows the
rules of a title
center() Returns a centered string
isupper() Returns True if all characters in the
count() Returns the number of times a string are upper case
specified value occurs in a string
join() Joins the elements of an iterable to
encode() Returns an encoded version of the the end of the string
string
ljust() Returns a left justified version of the
endswith() Returns true if the string ends with string
the specified value
lower() Converts a string into lower case
expandtabs() Sets the tab size of the string
lstrip() Returns a left trim version of the
find() Searches the string for a specified string
value and returns the position of
where it was found maketrans() Returns a translation table to be used
in translations
format() Formats specified values in a string
partition() Returns a tuple where the string is
format_map() Formats specified values in a string parted into three parts
index() Searches the string for a specified replace() Returns a string where a specified
3 value and returns the position of value is replaced with a specified
where it was found value
isalnum() Returns True if all characters in the rfind() Searches the string for a specified

Huy init | https://www.facebook.com/huyinit13


print(bool(""))
value and returns the last position of
print(bool(()))
where it was found
print(bool([]))
rindex() Searches the string for a specified print(bool({}))
value and returns the last position of def myFunction() :
where it was found return True
print("end ",myFunction())
rjust() Returns a right justified version of the True
string False
False
rpartition() Returns a tuple where the string is True
parted into three parts True
False
rsplit() Splits the string at the specified False
separator, and returns a list False
False
rstrip() Returns a right trim version of the False
string False
False
split() Splits the string at the specified end True
separator, and returns a list
Bộ sưu tập Python (Mảng)
splitlines() Splits the string at line breaks and Có bốn kiểu dữ liệu thu thập trong ngôn ngữ lập trình
returns a list Python:
 Danh sách là một tập hợp được sắp xếp và có
startswith() Returns true if the string starts with
thể thay đổi. Cho phép các thành viên trùng
the specified value
lặp.
strip() Returns a trimmed version of the  Tuple là một bộ sưu tập có thứ tự và không
string thể thay đổi. Cho phép các thành viên trùng
lặp.
swapcase() Swaps cases, lower case becomes  Tập hợp là một tập hợp không có thứ tự và
upper case and vice versa không được lập chỉ mục. Không có thành viên
trùng lặp.
title() Converts the first character of each  Từ điển là một bộ sưu tập không có thứ tự và
word to upper case có thể thay đổi. Không có thành viên trùng
lặp.
translate() Returns a translated string Khi chọn một kiểu tập hợp, sẽ rất hữu ích khi hiểu các
thuộc tính của kiểu đó. Chọn loại phù hợp cho một tập
upper() Converts a string into upper case dữ liệu cụ thể có thể có nghĩa là duy trì ý nghĩa và, nó
có thể có nghĩa là tăng hiệu quả hoặc bảo mật.
zfill() Fills the string with a specified
number of 0 values at the beginning Python Lists
thislist = ["apple", "banana", "cherry"]
Python Booleans print(thislist)
print(10 > 9) print(len(thislist))
print(10 == 9) print(type(thislist))
print(10 < 9)
print(bool("Hello")) list1 = ["abc", 34, True, 40, "male"]
4 print(bool(15)) print(list1)
print(bool(False)) print(type(list1))
print(bool(None)) ['apple', 'banana', 'cherry']
print(bool(0)) 3

Huy init | https://www.facebook.com/huyinit13


<class 'list'> #print(len(thislist)) : #this will cause an error because
['abc', 34, True, 40, 'male'] you have succsesfully deleted "thislist".
<class 'list'> ['apple', 'cherry', 'union', 'peach']
['apple', 'union', 'peach']
['apple', 'peach']
Python - Access List Items ['apple']
thislist = ["apple", "banana", "cherry", "orange", []
"kiwi", "melon", "mango"]
print(thislist[1]) Python - Loop Lists
print(thislist[-1]) thislist = ["apple", "banana", "cherry"]
print(thislist[2:5]) for x in thislist:
print(thislist[:4]) print(x,end=' ')
print(thislist[2:]) print()
print(thislist[-4:-1]) for i in range(len(thislist)):
if "apple" in thislist: print(thislist[i],end=' ')
print("Yes, 'apple' is in the fruits list") print()
banana i=0
mango while i < len(thislist):
['cherry', 'orange', 'kiwi'] print(thislist[i],end=' ')
['apple', 'banana', 'cherry', 'orange'] i=i+1
['cherry', 'orange', 'kiwi', 'melon', 'mango'] print()
['orange', 'kiwi', 'melon'] [print(x,end=' ') for x in thislist]
Yes, 'apple' is in the fruits list apple banana cherry
apple banana cherry
Python - add List Items apple banana cherry
thislist = ["apple", "banana", "cherry"] apple banana cherry
thislist[1] = "watermelon"
print(thislist)
thislist.insert(2, "kiwi") Python - Sort Lists
print(thislist)
thislist.append("orange") thislist = ["orange", "mango", "kiwi", "pineapple",
print(thislist) "banana"]
['apple', 'watermelon', 'cherry'] thislist.sort()
['apple', 'watermelon', 'kiwi', 'cherry'] print(thislist)
['apple', 'watermelon', 'kiwi', 'cherry', 'orange'] thislist.sort(reverse = True)
print(thislist)

Python - Remove List Items thislist = [100, 50, 65, 82, 23]
thislist = ["apple", "banana", thislist.sort()
"cherry","union","peach"] print(thislist)
thislist.remove("banana") def myfunc(n):
print(thislist) return abs(n - 50)
thislist.pop(1) thislist.sort(key = myfunc)
print(thislist) print(thislist)
del thislist[1]
print(thislist) thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.pop() thislist.sort()
print(thislist) print(thislist)
5 thislist.clear() thislist.sort(key = str.lower)
print(thislist) print(thislist)
del thislist thislist.reverse()
print(thislist)

Huy init | https://www.facebook.com/huyinit13


['banana', 'kiwi', 'mango', 'orange', 'pineapple']
insert() Adds an element at the specified position
['pineapple', 'orange', 'mango', 'kiwi', 'banana']
[23, 50, 65, 82, 100]
[50, 65, 23, 82, 100] pop() Removes the element at the specified
['Kiwi', 'Orange', 'banana', 'cherry'] position
['banana', 'cherry', 'Kiwi', 'Orange']
['Orange', 'Kiwi', 'cherry', 'banana'] remove() Removes the item with the specified value

thislist = ["apple", "banana", "cherry"] reverse() Reverses the order of the list
mylist = thislist.copy()
print(mylist)
mylist = list(thislist) sort() Sorts the list
print(mylist)
['apple', 'banana', 'cherry']
['apple', 'banana', 'cherry'] Python Tuples
Tuples are used to store multiple items in a single
Python - List Methods variable.
list1 = ["a", "b", "c"] A tuple is a collection which is ordered and
list2 = [1, 2, 3] unchangeable.
list3 = list1 + list2 Tuples are written with round brackets.
print(list3)
list3=list1 Tuples được sử dụng để lưu trữ nhiều mục trong một
for x in list2: biến duy nhất.
list3.append(x) Bộ tuple là một bộ sưu tập được sắp xếp theo thứ tự
print(list3) và không thể thay đổi .
['a', 'b', 'c', 1, 2, 3] Tuples được viết bằng dấu ngoặc tròn.
['a', 'b', 'c', 1, 2, 3] basic
thistuple = ("apple", "banana", "cherry")
List Methods print(thistuple)
Python has a set of built-in methods that you can use print(len(thistuple))
on lists. ('apple', 'banana', 'cherry')
3
Method Description
thistuple = ("apple",)#you have to add a comma
append() Adds an element at the end of the list print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
clear() Removes all the elements from the list print(type(thistuple))

tuple1 = ("abc", 34, True, 40, "male")


copy() Returns a copy of the list print(tuple1)
<class 'tuple'>
<class 'str'>
count() Returns the number of elements with the
('abc', 34, True, 40, 'male')
specified value

extend() Add the elements of a list (or any Python - Access Tuple Items

6 iterable), to the end of the current list


thistuple = ("apple", "banana", "cherry", "orange",
index() Returns the index of the first element with "kiwi", "melon", "mango")
the specified value print(thistuple[1])
print(thistuple[-1])

Huy init | https://www.facebook.com/huyinit13


print(thistuple[2:5]) while i < len(thistuple):
print(thistuple[:4]) print(thistuple[i],end=' ')
print(thistuple[2:]) i=i+1
print(thistuple[-4:-1]) apple banana cherry
if "apple" in thistuple: apple banana cherry
print("Yes, 'apple' is in the fruits tuple") apple banana cherry

banana Python - Join Tuples


mango tuple1 = ("a", "b" , "c")
('cherry', 'orange', 'kiwi') tuple2 = (1, 2, 3)
('apple', 'banana', 'cherry', 'orange') tuple3 = tuple1 + tuple2
('cherry', 'orange', 'kiwi', 'melon', 'mango') print(tuple3)
('orange', 'kiwi', 'melon') mytuple = tuple1 * 2
Yes, 'apple' is in the fruits tuple print(mytuple)
('a', 'b', 'c', 1, 2, 3)
Python - Update Tuples ('a', 'b', 'c', 'a', 'b', 'c')
Once a tuple is created, you cannot change its values.
Tuples are unchangeable, or immutable as it also is Tuple Methods
called. Python has two built-in methods that you can use on
But there is a workaround. You can convert the tuple tuples.
into a list, change the list, and convert the list back
Method Description
into a tuple.
thistuple = ("apple", "banana", "cherry")
y = list(thistuple) count() Returns the number of times a specified
y.append("orange") value occurs in a tuple
thistuple = tuple(y)
print(thistuple) index() Searches the tuple for a specified value and
#Remove Items : same returns the position of where it was found
('apple', 'banana', 'cherry', 'orange')
Python Sets
fruits = ("apple", "banana", "cherry")
Sets are used to store multiple items in a single
(green, yellow, red) = fruits
variable.
print(green,yellow,red)
A set is a collection which is both unordered and
fruits = ("apple", "banana", "cherry", "strawberry",
unindexed.
"raspberry")
Sets are written with curly brackets.
(green, yellow, *red) = fruits
Tập hợp được sử dụng để lưu trữ nhiều mục trong một
print(green,yellow,end=' ')
biến duy nhất.
print(red)#assigned to the variable as a list
Một tập hợp là một bộ sưu tập mà là cả hai không có
apple banana cherry
thứ tự và unindexed .
apple banana ['cherry', 'strawberry', 'raspberry']
Tập hợp được viết bằng dấu ngoặc nhọn.
basic:
# Note: the set list is unordered, meaning: the items
Python - Loop Tuples
will appear in a random order.
# Refresh this page to see the change in the result.
thistuple = ("apple", "banana", "cherry")
#Sets cannot have two items with the same value.
for x in thistuple:
thisset = {"apple", "banana", "cherry"}
print(x,end=' ')
print(thisset)
print()
7 print(len(thisset))
for i in range(len(thistuple)):
print(type(thisset))
print(thistuple[i],end=' ')
{'apple', 'banana', 'cherry'}
print()
3
i=0
<class 'set'>
Huy init | https://www.facebook.com/huyinit13
Access Set Items print(x,end=' ')
thisset = {"apple", "banana", "cherry"} print()
for x in thisset:
print(x,end=' ') banana apple cherry
print() Python - Join Sets
print("banana" in thisset) set1 = {"a", "b" , "c"}
cherry apple banana set2 = {1, 2, 3}
True set3 = set1.union(set2)
Python - Add Set Items print(set3)
thisset = {"apple", "banana"} set1.update(set2)
thisset.add("orange") print(set1)
print(thisset) {'a', 1, 2, 3, 'c', 'b'}
tropical = {"pineapple",} {'a', 1, 2, 3, 'c', 'b'}
thisset.update(tropical)
print(thisset) x = {"apple", "banana", "cherry"}
#it can be any iterable object (tuples, lists, dictionaries y = {"google", "microsoft", "apple"}
etc.). x.intersection_update(y)
mylist = ["kiwi", "orange"] print(x)
thisset.update(mylist) z = x.intersection(y)
print(thisset) print(z)
{'banana', 'orange', 'apple'} x = {"apple", "banana", "cherry"}
{'banana', 'orange', 'pineapple', 'apple'} y = {"google", "microsoft", "apple"}
{'apple', 'kiwi', 'banana', 'orange', 'pineapple'} x.symmetric_difference_update(y)
print(x)
Python - Remove Set Items z = x.symmetric_difference(y)
#If the item to remove does not exist, remove() will print(z)
raise an error. {'apple'}
thisset = {"apple", "banana", "cherry","kiwi","oil"} {'apple'}
thisset.remove("banana") {'banana', 'google', 'cherry', 'microsoft'}
print(thisset) {'banana', 'apple', 'cherry'}
#If the item to remove does not exist, discard() will
NOT raise an error. Set Methods
thisset.discard("apple") Python has a set of built-in methods that you can use
print(thisset) on sets.
x = thisset.pop()
Method Description
print(x)
print(thisset)
thisset.clear() add() Adds an element to the set
print(thisset)
del thisset
# print(thisset) sẽ bị lỗi clear() Removes all the elements from
{'kiwi', 'oil', 'cherry', 'apple'} the set
{'kiwi', 'oil', 'cherry'}
kiwi copy() Returns a copy of the set
{'oil', 'cherry'}
set()
difference() Returns a set containing the
difference between two or
8 Python - Loop Sets more sets

difference_up Removes the items in this set


thisset = {"apple", "banana", "cherry"}
date() that are also included in
for x in thisset:

Huy init | https://www.facebook.com/huyinit13


Từ điển là một tập hợp được sắp xếp theo thứ tự *, có
another, specified set
thể thay đổi và không cho phép trùng lặp.
Từ điển được viết bằng dấu ngoặc nhọn và có các
khóa và giá trị:
discard() Remove the specified item Basic:
thisdict = {
"brand": "Ford",
intersection() Returns a set, that is the "model": "Mustang",
intersection of two other sets "year": 1964,
"year": 2020
intersection_u Removes the items in this set
pdate() that are not present in other, }
specified set(s) print(thisdict)
print(thisdict["brand"])
isdisjoint() Returns whether two sets have print(len(thisdict))
a intersection or not print(type(thisdict))
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
issubset() Returns whether another set Ford
contains this set or not 3
<class 'dict'>
issuperset() Returns whether this set
contains another set or not
Python - Access Dictionary Items
pop() Removes an element from the thisdict = {
set "brand": "Ford",
"model": "Mustang",
remove() Removes the specified element "year": 1964
}
print(thisdict["model"])
symmetric_dif Returns a set with the x = thisdict["model"]
ference() symmetric differences of two print(x)
sets x = thisdict.get("model")
print(x)
symmetric_dif inserts the symmetric x = thisdict.keys()
ference_updat differences from this set and print(x)
e() another thisdict["name"]="huy"
print(thisdict.keys())
union() Return a set containing the x = thisdict.values()
union of sets print(x)
thisdict["name"]="HUY"
update() Update the set with the union print(thisdict.values())
of this set and others if "model" in thisdict:
print("Yes, 'model' is in the thisdict dictionary")
#The items() method will return each item in a
Python Dictionaries dictionary, as tuples in a list.Make a change in the
Dictionaries are used to store data values in key:value original dictionary, and see that the items list gets
pairs. updated as well:
A dictionary is a collection which is ordered*, x = thisdict.items()
changeable and does not allow duplicates. print(x)
9 Dictionaries are written with curly brackets, and have Mustang
keys and values: Mustang
Từ điển được sử dụng để lưu trữ các giá trị dữ liệu Mustang
trong các cặp key: value. dict_keys(['brand', 'model', 'year'])

Huy init | https://www.facebook.com/huyinit13


dict_keys(['brand', 'model', 'year', 'name']) print()
dict_values(['Ford', 'Mustang', 1964, 'huy']) for x in thisdict.keys():
dict_values(['Ford', 'Mustang', 1964, 'HUY']) print(x,end=' ')
Yes, 'model' is in the thisdict dictionary print()
dict_items([('brand', 'Ford'), ('model', 'Mustang'), for x, y in thisdict.items():
('year', 1964), ('name', 'HUY')]) print(x, y,end=' ')
print()
brand model year
Python - Change Dictionary Items Ford Mustang 1964
thisdict = { Ford Mustang 1964
"brand": "Ford", brand model year
"model": "Mustang", brand Ford model Mustang year 1964
"year": 1964
}
thisdict["year"] = 2018 Python - Copy Dictionaries
print(thisdict) thisdict = {
thisdict.update({"year": 2020}) "brand": "Ford",
print(thisdict) "model": "Mustang",
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018} "year": 1964
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020} }
mydict = thisdict.copy()
Python - Remove Dictionary Items print(mydict)
thisdict = { mydict = dict(thisdict)
"brand": "Ford", print(mydict)
"model": "Mustang", {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
"year": 1964, {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
"name":"Huy"
} Python - Nested Dictionaries : từ điển lồng
thisdict.pop("model") child1 = {
print(thisdict) "name" : "Emil",
thisdict.popitem()#removes the last inserted item "year" : 2004
print(thisdict) }
thisdict.clear() child2 = {
print(thisdict) "name" : "Tobias",
{'brand': 'Ford', 'year': 1964, 'name': 'Huy'} "year" : 2007
{'brand': 'Ford', 'year': 1964} }
{} child3 = {
"name" : "Linus",
Python - Loop Dictionaries "year" : 2011
thisdict = { }
"brand": "Ford",
"model": "Mustang", myfamily = {
"year": 1964 "child1" : child1,
} "child2" : child2,
for x in thisdict: "child3" : child3
print(x,end=' ') }
print() print(myfamily)
for x in thisdict: {'child1': {'name': 'Emil', 'year': 2004}, 'child2':
10 print(thisdict[x],end=' ') {'name': 'Tobias', 'year': 2007}, 'child3': {'name':
print() 'Linus', 'year': 2011}}
for x in thisdict.values():
print(x,end=' ') Dictionary Methods

Huy init | https://www.facebook.com/huyinit13


Python has a set of built-in methods that you can use print("A") if a > b else print("B")
on dictionaries. c = 500
if a > b and c > a:
Method Description
print("Both conditions are True")
clear() Removes all the elements from the if a > b or a > c:
dictionary print("At least one of the conditions is True")
a is greater than b
copy() Returns a copy of the dictionary a is greater than b
A
fromkeys() Returns a dictionary with the specified Both conditions are True
keys and value At least one of the conditions is True

get() Returns the value of the specified key


Python While Loops
items() Returns a list containing a tuple for each i = 1
key value pair while i < 6:
print(i,end=' ')
keys() Returns a list containing the dictionary's i += 1
keys else:
print("\ni is no longer less than 6")
pop() Removes the element with the specified 1 2 3 4 5
key i is no longer less than 6

popitem() Removes the last inserted key-value pair


Python For Loops
setdefault() Returns the value of the specified key. If fruits = ["apple", "banana", "cherry"]
the key does not exist: insert the key, for x in fruits:
with the specified value print(x)
if x == "banana":break
update() Updates the dictionary with the for x in fruits:
specified key-value pairs if x == "banana":continue
print(x)
values() Returns a list of all the values in the for x in range(6):
dictionary print(x,end= ' ')
else:
print("Finally finished!")
apple
Python If ... Else banana
#The elif keyword is pythons way of saying "if the apple
previous conditions were not true, then try this cherry
condition". 0 1 2 3 4 5 Finally finished!
#The else keyword catches anything which isn't
caught by the preceding conditions. Python Functions
# and+or
def my_function(fname):
a = 200
print(fname + " Refsnes")
b = 33
my_function("Emil")
if b > a:
print("b is greater than a")
def my_function1(country = "Norway"):
elif a == b:
11 print("I am from " + country)
print("a and b are equal")
my_function1("India")
else:
my_function1()
print("a is greater than b")
if a > b: print("a is greater than b")
def my_function3(x):
Huy init | https://www.facebook.com/huyinit13
return 5 * x 3
print(my_function3(3)) Toyota Volvo BMW
print(my_function3(5)) ['Toyota', 'Volvo', 'BMW', 'Honda']
Emil Refsnes ['Toyota', 'Volvo', 'BMW']
I am from India
I am from Norway
15
25

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result,end=' ')
else:
result = 0
return result
tri_recursion(6)
1 3 6 10 15 21

Python Lambda (ẩn danh)


x = lambda a: a + 10
print(x(5))
x = lambda a, b: a * b
print(x(5, 6))
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
15
30
13

Python Arrays
Note: This page shows you how to use LISTS as
ARRAYS, however, to work with arrays in Python
you will have to import a library, like the NumPy
library.
cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)
x = len(cars)
print(x)
for x in cars:
print(x,end=' ')
cars.append("Honda")
12 print('\n',cars)
cars.pop(3)
print(cars)
['Toyota', 'Volvo', 'BMW']

Huy init | https://www.facebook.com/huyinit13

You might also like