目錄
- 一、PEP 8 規范
- 二、變數和簡單資料型別
- 三、串列
- 四、if和回圈
- 五、元組
- 六、字典
- 七、函式
- 八、類
- 九、檔案讀寫
- 十、例外
- 十一、測驗代碼
一、PEP 8 規范
撰寫代碼時,符合規范這對大家都好,下面僅僅是一方面,還有很多規范,更多可以參考python PEP 8檔案
1、每級縮進四個空格
2、每行都不要超過80個字符
3、不要在程式檔案中使用過多空行
4、注釋 # 后 要有一個空格
5、采用駝峰命名法
6、單引號和雙引號作用相同
7、陳述句結尾可省略分號
二、變數和簡單資料型別
python宣告變數時,不用指明資料型別,解釋器會根據實際資料型別自動推導
1、變數
name = "John"
number = 4
print(type(name))
print(type(number))
print(type(number2))
---------------------------------------
# 結果
<class 'str'>
<class 'int'>
<class 'float'>
2、字串
first_name = "ada"
last_name = "dddd"
full_name = f"{first_name} {last_name}"
message = f"Hello,{full_name.title()}!"
print(message)
f:是format 簡寫,通過花括號內的變數替換為其值來設定字串的格式
title() :將字串首字母大寫
rstrip() :剔除字串右邊的空白
lstrip() :剔除字串左邊的空白
strip() : 剔除字串兩邊的空白
name = " python"
print(name)
print(name.strip())
-------------------------------------
# 結果
python
python
3、數
乘方
# 計算4的三次方
print(4**3)
------------------------
# 結果
64
使用_對數字進行 分組 使其更加清晰
number3 = 10_000_000
print(number3)
-------------------------
# 結果
10000000
三、串列
dogs = ["a", "d", "e", "f"]
print(dogs)
dogs.insert(1, "g") # 在串列下標為1增加一個元素
del dogs[0] # 洗掉串列中小標為0
dogs[2] = "m" # 修改
dogs.append("w") # 末尾追加
print(dogs)
x = dogs.pop() # 洗掉末尾元素并回傳 類似于堆疊
print(x)
print(len(dogs)) # 求長度
dogs.remove("d") # 根據值洗掉
print(dogs)
dogs.reverse() # 將串列反轉
print(dogs)
-------------------------------------------
# 結果
['a', 'd', 'e', 'f']
['g', 'd', 'm', 'f', 'w']
w
4
['g', 'm', 'f']
['f', 'm', 'g']
Process finished with exit code 0
2、切片
處理串列的一部分元素,稱之為切片
players = ["ok", "sw", "dw", "oo", "fs"]
print(players[1:3]) # 回傳索引 1-2的元素
print(players[1:]) # 回傳索引 1-串列末尾的元素
'''
兩邊都為空表示 回傳從頭到尾的元素
'''
gamer = players[:]
print(gamer)
--------------------------
['sw', 'dw']
['sw', 'dw', 'oo', 'fs']
['ok', 'sw', 'dw', 'oo', 'fs']
3、復制串列
四、if和回圈
elif 就相當于 else if
b = eval(input("請輸入:")) # 型別轉換成 輸入的型別 自動轉換
if b >= 18:
print("hello")
elif b >= 13:
print("Yes")
elif b >= 8:
print("happy")
else:
print("No")
for i in range(b): # [0,b)
print(i)
for i in range(10, 30): # [10,30)
print(i)
for i in range(10, 30, 2): # [10,30) 步長為2
print(i)
while i <= 5:
print(i)
i+=1
numbers = list(range(5, 10)) # 轉換成串列輸出
print(numbers)
-------
[5, 6, 7, 8, 9]
numbers = range(1, 20)
print(min(numbers)) # 求最小值
print(sum(numbers)) # 求最和
print(min(numbers)) # 求最小值
-----------------------
1
190
19
五、元組
串列適合用于存盤在程式運行期間可能引起變化的資料集,串列是可以修改
不可變的串列稱為元組.
dimensions = (20, 60, 80)
print(dimensions[0])
print(dimensions)
--------------------------------
20
(20, 60, 80)
六、字典
字典相當于java中的map集合,使用鍵值對存盤資料
cats = {"name": "john", "age": 20}
print(cats)
a = cats.get("name", "john")
print(cats.values())
for key, value in cats.items():
print(f"{key}")
print(f"{value}")
-------------------------------
{'name': 'john', 'age': 20}
dict_values(['john', 20])
{'name': 'john', 'age': 20}
dict_values(['john', 20])
name
john
age
20
"""
items:回傳所有鍵值對串列
keys:回傳所有鍵
valuse:回傳所有值
"""
字典也可以存盤串列
users = {"manage": {
"name": "Tom",
"age": 30,
"location": "A",
},
"student": {
"name":"mae",
"age":20,
"location":"S",
},
}
-----------------------------------
{'manage': {'name': 'Tom', 'age': 30, 'location': 'A'}, 'student': {'name': 'mae', 'age': 20, 'location': 'S'}}
七、函式
定義:
def 函式名(形式引數)
def amb(a, b):
return (a + b) ** 2
print(amb(1, 3))
# 可以使用默認值
def amb(a, b=3):
return (a + b) ** 2
print(amb(1))
-------------------------
16
16
# 如何傳任意個數的實參 args 相當于一個元組 與java相同
def js(*args):
print(args)
js("a", "b", "c")
js("e", "f")
('a', 'b', 'c')
('e', 'f')
將函式存盤在模板中
# test07
def amb(a, b=3):
return (a + b) ** 2
---------------------
"""
improt test07 as t:匯入整個模板 as可以起別名 非必選
t.amb(2, 3)
"""
from test07 import amb #匯入特定的函式
print(amb(1, 2))
八、類
init():為建構式
形參self必不可少
每個方法定義都有self,以self為前綴的變數可供類中所有的方法適合于
# test09
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bite(self):
print("wangwang")
---------------------------------
import test09 as t
my_dog = t.Dog('Yel', 5)
my_dog.bite()
---------------------------------
# 結果:
wangwang
繼承:
在繼承類定義在類名后加括號寫上繼承的類
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bite(self):
print("wangwang")
class BlueDog(Dog):
def __init__(self, name, age, log):
super().__init__(name, age)
self.log = log
def describe(self):
print(f"{self.name} {self.age} {self.log}")
---------------------------------------------
Wa 20 mm
九、檔案讀寫
# 寫入檔案
with open("username", 'w') as file_object:
file_object.write("I Love Python\n")
file_object.write("I also love Java\n")
-----------------------------
I Love Python
I also love Java
"""
第二個引數
w:表示寫,會覆寫原有內容
a: 表示在原有檔案后追加內容
"""
# 讀取檔案
with open("username") as file_object2:
contents = file_object2.read()
print(contents)
"""
readlines():表示讀取一行
"""
with open("username") as file_object2:
lines = file_object2.readlines()
p_string = ''
for line in lines:
p_string += line.rstrip()
print(p_string)
--------------------------------------
I Love PythonI also love Java
十、例外
1、ZeroDivisionError 例外
try:
print(5 / 0)
except ZeroDivisionError:
print("not divide by zero!"
-----------------------------------
not divide by zero!
2、FileNotFoundError 例外
try:
with open("username", 'w') as file_object:
file_object.write("I Love Python\n")
file_object.write("I also love Java\n")
except FileNotFoundError:
print("File not exist")
3、else 代碼塊
a = int(input("input a number: "))
try:
b = 5 / a
except ZeroDivisionError:
print("not divide by zero!")
else:
print(b)
-----------------------------
input a number: 0
not divide by zero!
input a number: 1
5.0
十一、測驗代碼
# test09
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bite(self):
print("wangwang")
class BlueDog(Dog):
def __init__(self, name, age, log):
super().__init__(name, age)
self.log = log
def describe(self):
print(f"{self.name} {self.age} {self.log}")
------------------------------------------------
import unittest
import test09 as t
class DogTestCase(unittest.TestCase):
def test_describe(self):
my_dog = t.BlueDog("john", 18, "hahaha")
my_dog.describe()
# 運行結果:
Testing started at 22:10 ...
Ran 1 test in 0.003s
OK
Launching unittests with arguments python -m unittest test12.DogTestCase.test_describe in D:\pythonProject\Exer
Process finished with exit code 0
john 18 hahaha
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350960.html
標籤:python
