iT邦幫忙

2021 iThome 鐵人賽

DAY 3
1
自我挑戰組

月光下的Flask之旅系列 第 3

Day 03 Python 入門

因為考慮到才第三篇就開始飆車直接上 Flask 會不會太快,加上這系列有一小部分原因(大約50%?)是要寫給以後完全忘掉這些的自己,再加上 Python 跟其他程式語言有一點點不太一樣,有一些眉角需要注意(像是下圖的波動拳縮排,不小心少縮了一個就會出大事),所以就先來回憶一下 Python 了。下一篇就會說到比較進階,需要挖比較深才會碰到的東西。

開始

開始講之前先講一下寫好要怎麼存好了,就是寫完存成.py檔,然後在 CMD (檔案總管中你存的位置上面那條輸入 CMD,大小寫都可),再輸入 python <name>.py 就 OK 了。

資料型態

Python 中主要有十幾種資料型態

Type Name
字串 str
數字 int, float, complex
序列 list, tuple, range
字典 dict
集合 set, frozenset
布林 bool
位元 bytes, bytearray, memoryview

雖然有這麼多種,但是最常用還是 str, int, float, list, range, dict, bool 這7種。

使用方式為

''' Input '''
# 賦值
string = 'Hello'
num1 = 10
num2 = 20
l = ['a', 'b', 'c']
d = {'apple': 'red', 1: 'banana'} # or d = dict(apple='red')
# 沒錯 dict 的 key 可以用 str 或 int

# 取值
print(string)
print(num1 + num2)
print(l[1])
print(d['apple'])
print(d[1])


''' Output '''
Hello
30
b
red
banana

Python 雖然有 PEP8 可以統一 Coding Style,但是 PEP8 並不會管到變數、函數及類別的名稱。不過有關這些名稱也有一些命名規則,雖然不按規則也不會怎樣,但是按照規則的話以後在維護時會更容易解讀。

條件選擇

我不知道該怎麼解釋,所以算了,直接看範例吧。主要注意一下縮排跟冒號是必不可少的就好了。

''' Input '''
age = int(input('Input a number: '))  # 可以執行起來後輸入數字,如果輸入 20
if age >= 20:
    print('You are an adult.')
elif age >= 12: 
    print('You are a teenager.')
else:
    print('You are a child.')


''' Output '''
You are an adult.

迴圈

需要注意的點跟前面的條件選擇一樣,然後就沒有然後了,一樣直接看範例吧。

For 迴圈

''' Input '''
for i in range(1, 10, 2):
    mes = ""
    for j in range(i):
        mes += "*"
    print('{:^9}'.format(mes))


''' Output '''
    *
   ***
  *****
 *******
*********

While 迴圈

''' Input '''
i = 1
while i < 10:
    print(i, end=', ')
    i = i + 1

''' Output '''
1, 2, 3, 4, 5, 6, 7, 8, 9, 

Function(函式)

需要注意的點基本上跟前面兩個一樣,然後再加個小括號,小括號中間填要帶入的參數就好了。

# J個是前面那個星星金字塔的函式版本
def star_triangle(times):
    for i in range(1, times+1, 2):
        step = ""
        for j in range((times-i)//2):
            step += " "
        for j in range(i):
            step += "*"
        print(step)

Class(類別)

''' Input '''
class Car():
    _manufacturer = ""
    
    def __init__(self, manufacturer, color):
        self._manufacturer = manufacturer
        self.color = color
    
    def get_manufacturer(self):
        return self._manufacturer
    
    def change_color(self, color):
        self.color = color
    
    def get_color(self):
        return self.color

# SUVCar 繼承 Car
class SUVCar (Car):
    _car_type = "SUV"
    
    def __init__(self, manufacturer, color):
        super().__init__(manufacturer, color)
    
    def get_car_type(self):
        return self._car_type

new_car = SUVCar("BMW", "Black")

new_car.get_manufacturer()
new_car.get_color()
new_car.get_car_type()

new_car.change_color("White")
new_car.get_color()


''' Output '''
BMW
Black
SUV

White

參考資料

搞懂Python的內建型別

好了,基礎的就大概這樣子而已。

那麼就先到這邊,實際再寫的時候,有 80% 都是上面這些東西。

大家掰~掰~


上一篇
Day 02 環境建置
下一篇
Day 04 Python 進階
系列文
月光下的Flask之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言