Python Getting Started
資料來源
Complete-Python-3-Bootcamp @ GitHub
Setup & Installation
Anaconda
# 關掉 Anaconda 自動在 Terminal 中啟動 base environment "(base)"
$ conda config --set auto_activate_base false
# 啟動 Anaconda
$ conda activate
Data Structure Basic
Variable
a = 3
type(a) # int
String
##
# Index and Slice
##
'tinker'[1:4] # 'ink'
'tinker'[1:4:2] # 'ik'
'tinker'[::-1] # 'reknit
##
# Formatting with the .format() method
##
'Good {}, {} Chen!'.format('morning', 'Mr.') # 'Good morning, Mr. Chen!'
'My favorite brand is {}, {}, and {}!'.format('Apple', 'Samsung', 'Google') # 'My favorite brand is Apple, Samsung, and Google!'
'My favorite brand is {2}, {1}, and {0}!'.format('Apple', 'Samsung', 'Google') # 'My favorite brand is Google, Samsung, and Apple!'
'Repeat after me: {0}! {0}! {0}!'.format('Ho') # 'Repeat after me: Ho! Ho! Ho!'
'Good {time}, {title} {name}!'.format(time='morning', title='Mr.', name='Chen') # 'Good morning, Mr. Chen!'
##
# Float Formatting
##
result = 100/777 # 0.1287001287001287
# Old Way, {value:width.precision f}
print("The result was {:1.3f}".format(result)) # The result was 0.129
# Formatted String Literals(f-strings)
name = 'Aaron'
age = 33
print(f'Hello, my name is {name}, and I\'m {age} years old.')
List
[0]*3 # [0, 0, 0]
my_list = [1, 3, 2]
another_list = [4, 6, 5]
# array concat
whole_list = my_list + another_list
whole_list # [1, 3, 2, 4, 6, 5]
# sort
whole_list.sort()
whole_list # [1, 2, 3, 4, 5, 6]
whole_list.reverse()
whole_list # [6, 5, 4, 3, 2, 1]
Operators
Comparisons Operators
1 < 2 < 3 # True
1 < 2 and 2 < 3 # True
1 == 1 or 2 == 2 # True
not ( 1 == 1 ) # False
not ( 400 > 5000 ) # True
Useful Operators
range(start, stop, step)
# 0, 1, 2
for i in range(3):
print(i)
# 3, 4
for i in range(3,5):
print(i)
# 1,3,5
for i in range(1,6,2):
print(i)
# [0, 2, 4]
list(range(0, 5, 2))
enumerator
把 string 變成 tuple
word = 'abc'
# 0: a
# 1: b
# 2: c
for idx, value in enumerate(word):
print(f'{idx}: {value}')
zip
把多 個 list 組成一個 tuple
name = ['Aaron', 'John', 'Mary']
age = [12, 13, 14]
height = [170, 180, 160]
# Aaron is 12 years old with 170 cm
# John is 13 years old with 180 cm
# Mary is 14 years old with 160 cm
for name, age, height in zip(name, age, height):
print(f'{name} is {age} years old with {height} cm')
# <zip object at 0x1023a1300>
zip(name, age, height)
# [('Aaron', 12, 170), ('John', 13, 180), ('Mary', 14, 160)]
list(zip(name, age, height))
in
1 in [1, 2, 3] # True
'a' in 'abc' # True
'a' in [1, 2, 3] # False
user = {
"name": "John",
"age": 30,
"city": "New York"
}
'name' in user # True
'John' in user.values()
Statements
Conditional Statements
state = 'active'
if state == 'active':
print('The state is active')
elif state == 'inactive':
print('The state is inactive')
else:
print('The state is unknown')
For Loops
Iterate a list
brands = ['Ford', 'BMW', 'Volvo']
for brand in brands:
print(brand)
Combine with conditional statement:
brands = ['Ford', 'BMW', 'Volvo']
for brand in brands:
if brand == 'Volvo':
print(brand + ' - I like it!')
else:
print(brand + ' - I don\'t like it!')
Iterate a string
str = 'Hello World'
for letter in str:
print(letter)
Iterate a tuple
for t in (1, 2, 3):
print(t)
Tuple Unpacking
my_list = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
for a, b in my_list:
print(a + b)
Iterate an dictionary
user = {
"name": "John",
"age": 30,
"city": "New York"
}
for key in user:
print(f'key: {key}')
print(f'value: {user[key]}')
for key, value in user.items():
print(f'key: {key}')
print(f'value: {value}')
for value in user.values():
print(value)
While Loops
x = 0
while x < 5:
# x = x + 1
x += 1
print(f'The current value of x is {x}')
# could combine with "else"
else:
print('X IS NOT LESS THAN 5')
Basic I/O
Read and Write files
mode='r'
: read onlymode='w'
: write only (will overwrite existing files or create new)mode='a'
: append onlymode='r+'
: read and writemode='w+'
: write and read (overwrite existing files or create new)
myfile = open('myfile.txt')
myfile.read()
myfile.seek(0) # reset cursor
myfile.readlines() # returns a list of lines
myfile.close() # close file
# 不用怕忘記 close 的寫法
# create or overwrite a file
with open('myfile.txt', mode="w") as my_new_file:
contents = my_new_file.write(
'this is a text file\nthis is the second line\nthis is the third line')
# read file
with open('myfile.txt', mode='r') as f:
contents = f.read()
print(contents)
# append file
with open('myfile.txt', mode='a') as f:
f.write('\nthis is the fourth line')
with open('myfile.txt', mode='r') as f:
contents = f.read()
print(contents)