因为考虑到才第三篇就开始飙车直接上 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.
需要注意的点跟前面的条件选择一样,然後就没有然後了,一样直接看范例吧。
''' Input '''
for i in range(1, 10, 2):
mes = ""
for j in range(i):
mes += "*"
print('{:^9}'.format(mes))
''' Output '''
*
***
*****
*******
*********
''' Input '''
i = 1
while i < 10:
print(i, end=', ')
i = i + 1
''' Output '''
1, 2, 3, 4, 5, 6, 7, 8, 9,
需要注意的点基本上跟前面两个一样,然後再加个小括号,小括号中间填要带入的参数就好了。
# 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)
''' 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
好了,基础的就大概这样子而已。
那麽就先到这边,实际再写的时候,有 80% 都是上面这些东西。
大家掰~掰~
>>: 冒险村03 - Travis CI cookbook
URL Encoding(URL编码) URL 编码将字符转换为可以通过 Internet 传输的格...
今天来用 Cloudflare Workers 写个有趣的东西吧! 你的 IP 是不是 ? 很酷吧!...
其实原本最初规画想要做Index方式的纪录,然後多增加一些没写到的面向 不过,总是计画赶不上变化 ...
灵异现象 - 我根本没这个帐号阿 灵异现象 故事接着小新公司被入侵之後的延续, 小新在厂商调查的同时...
看来今天终於是可以把 Grafana 的章节结束掉了,之前提到我觉得目前找到的 dashboard ...