01-Hello World
python的語法邏輯完全靠縮進,建議縮進4個空格, 如果是頂級代碼,那么必須頂格書寫,哪怕只有一個空格也會有語法錯誤, 下面示例中,滿足if條件要輸出兩行內容,這兩行內容必須都縮進,而且具有相同的縮進級別,
print('hello world!')
if 3 > 0:
print('OK')
print('yes')
x = 3; y = 4 # 不推薦,還是應該寫成兩行
print(x + y)
02-print
print('hello world!')
print('hello', 'world!') # 逗號自動添加默認的分隔符:空格
print('hello' + 'world!') # 加號表示字符拼接
print('hello', 'world', sep='***') # 單詞間用***分隔
print('#' * 50) # *號表示重復50遍
print('how are you?', end='') # 默認print會列印回車,end=''表示不要回車
03-基本運算
運算子可以分為:算術運算子、比較運算子和邏輯運算子,優先級是:算術運算子>比較運算子>邏輯運算子,最好使用括號,增加了代碼的可讀性,
print(5 / 2) # 2.5
print(5 // 2) # 丟棄余數,只保留商
print(5 % 2) # 求余數
print(5 ** 3) # 5的3次方
print(5 > 3) # 回傳True
print(3 > 5) # 回傳False
print(20 > 10 > 5) # python支持連續比較
print(20 > 10 and 10 > 5) # 與上面相同含義
print(not 20 > 10) # False
04-input
number = input("請輸入數字: ") # input用于獲取鍵盤輸入
print(number)
print(type(number)) # input獲得的資料是字符型
print(number + 10) # 報錯,不能把字符和數字做運算
print(int(number) + 10) # int可將字串10轉換成數字10
print(number + str(10)) # str將10轉換為字串后實作字串拼接
05-輸入輸出基礎練習
username = input('username: ')
print('welcome', username) # print各項間默認以空格作為分隔符
print('welcome ' + username) # 注意引號內最后的空格
06-字串使用基礎
python中,單雙引號沒有區別,表示一樣的含義 這里免費送大家一套2020最新python入門到高級專案實戰視頻教程,可以去小編的Python交流.扣扣.裙 :879151479,還可以跟行業大牛交流討教!
sentence = 'tom\'s pet is a cat' # 單引號中間還有單引號,可以轉義
sentence2 = "tom's pet is a cat" # 也可以用雙引號包含單引號
sentence3 = "tom said:\"hello world!\""
sentence4 = 'tom said:"hello world"'
# 三個連續的單引號或雙引號,可以保存輸入格式,允許輸入多行字串
words = """
hello
world
abcd"""
print(words)
py_str = 'python'
len(py_str) # 取長度
py_str[0] # 第一個字符
'python'[0]
py_str[-1] # 最后一個字符
# py_str[6] # 錯誤,下標超出范圍
py_str[2:4] # 切片,起始下標包含,結束下標不包含
py_str[2:] # 從下標為2的字符取到結尾
py_str[:2] # 從開頭取到下標是2之前的字符
py_str[:] # 取全部
py_str[::2] # 步長值為2,默認是1
py_str[1::2] # 取出yhn
py_str[::-1] # 步長為負,表示自右向左取
py_str + ' is good' # 簡單的拼接到一起
py_str * 3 # 把字串重復3遍
't' in py_str # True
'th' in py_str # True
'to' in py_str # False
'to' not in py_str # True
07-串列基礎
串列也是序列物件,但它是容器型別,串列中可以包含各種資料
**alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
len(alist)
alist[-1] # 取出最后一項
alist[-1][-1] # 因為最后一項是串列,串列還可以繼續取下標
[1,2,3][-1] # [1,2,3]是串列,[-1]表示串列最后一項
alist[-2][2] # 串列倒數第2項是字串,再取出字符下標為2的字符
alist[3:5] # ['bob', 'alice']
10 in alist # True
'o' in alist # False
100 not in alist # True
alist[-1] = 100 # 修改最后一項的值
alist.append(200) # 向**串列中追加一項
08-元組基礎
元組與串列基本上是一樣的,只是元組不可變,串列可變,
atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])
len(atuple)
10 in atuple
atuple[2]
atuple[3:5]
# atuple[-1] = 100 # 錯誤,元組是不可變的
09-字典基礎
# 字典是key-value(鍵-值)對形式的,沒有順序,通過鍵取出值
adict = {'name': 'bob', 'age': 23}
len(adict)
'bob' in adict # False
'name' in adict # True
adict['email'] = '[email protected]' # 字典中沒有key,則添加新專案
adict['age'] = 25 # 字典中已有key,修改對應的value
10-基本判斷
單個的資料也可作為判斷條件, 任何值為0的數字、空物件都是False,任何非0數字、非空物件都是True,
if 3 > 0:
print('yes')
print('ok')
if 10 in [10, 20, 30]:
print('ok')
if -0.0:
print('yes') # 任何值為0的數字都是False
if [1, 2]:
print('yes') # 非空物件都是True
if ' ':
print('yes') # 空格字符也是字符,條件為True
11-條件運算式、三元運算子
a = 10
b = 20
if a < b:
smaller = a
else:
smaller = b
print(smaller)
s = a if a < b else b # 和上面的if-else陳述句等價
print(s)
12-判斷練習:用戶名和密碼是否正確
import getpass # 匯入模塊
username = input('username: ')
# getpass模塊中,有一個方法也叫getpass
password = getpass.getpass('password: ')
if username == 'bob' and password == '123456':
print('Login successful')
else:
print('Login incorrect')
13-猜數:基礎實作
import random
num = random.randint(1, 10) # 隨機生成1-10之間的數字
answer = int(input('guess a number: ')) # 將用戶輸入的字符轉成整數
if answer > num:
print('猜大了')
elif answer < num:
print('猜小了')
else:
print('猜對了')
print('the number:', num)
14-成績分類1
score = int(input('分數: '))
if score >= 90:
print('優秀')
elif score >= 80:
print('好')
elif score >= 70:
print('良')
elif score >= 60:
print('及格')
else:
print('你要努力了')
15-成績分類2
score = int(input('分數: '))
if score >= 60 and score < 70:
print('及格')
elif 70 <= score < 80:
print('良')
elif 80 <= score < 90:
print('好')
elif score >= 90:
print('優秀')
else:
print('你要努力了')
16-石頭剪刀布
import random
all_choices = ['石頭', '剪刀', '布']
computer = random.choice(all_choices)
player = input('請出拳: ')
# print('Your choice:', player, "Computer's choice:", computer)
print("Your choice: %s, Computer's choice: %s" % (player, computer))
if player == '石頭':
if computer == '石頭':
print('平局')
elif computer == '剪刀':
print('You WIN!!!')
else:
print('You LOSE!!!')
elif player == '剪刀':
if computer == '石頭':
print('You LOSE!!!')
elif computer == '剪刀':
print('平局')
else:
print('You WIN!!!')
else:
if computer == '石頭':
print('You WIN!!!')
elif computer == '剪刀':
print('You LOSE!!!')
else:
print('平局')
17-改進的石頭剪刀布
import random
all_choices = ['石頭', '剪刀', '布']
win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['布', '石頭']]
prompt = """(0) 石頭
(1) 剪刀
(2) 布
請選擇(0/1/2): """
computer = random.choice(all_choices)
ind = int(input(prompt))
player = all_choices[ind]
print("Your choice: %s, Computer's choice: %s" % (player, computer))
if player == computer:
print('\033[32;1m平局\033[0m')
elif [player, computer] in win_list:
print('\033[31;1mYou WIN!!!\033[0m')
else:
print('\033[31;1mYou LOSE!!!\033[0m')
18-猜數,直到猜對
import random
num = random.randint(1, 10)
running = True
while running:
answer = int(input('guess the number: '))
if answer > num:
print('猜大了')
elif answer < num:
print('猜小了')
else:
print('猜對了')
running = False
19-猜數,5次機會
import random
num = random.randint(1, 10)
counter = 0
while counter < 5:
answer = int(input('guess the number: '))
if answer > num:
print('猜大了')
elif answer < num:
print('猜小了')
else:
print('猜對了')
break
counter += 1
else: # 回圈被break就不執行了,沒有被break才執行
print('the number is:', num)
20-while回圈,累加至100
因為回圈次數是已知的,實際使用時,建議用for回圈
sum100 = 0
counter = 1
while counter < 101:
sum100 += counter
counter += 1
print(sum100)
21-while-break
break是結束回圈,break之后、回圈體內代碼不再執行,
while True:
yn = input('Continue(y/n): ')
if yn in ['n', 'N']:
break
print('running...')
22-while-continue
計算100以內偶數之和,
continue是跳過本次回圈剩余部分,回到回圈條件處,
sum100 = 0
counter = 0
while counter < 100:
counter += 1
# if counter % 2:
if counter % 2 == 1:
continue
sum100 += counter
print(sum100)
23-for回圈遍歷資料物件
astr = 'hello'
alist = [10, 20, 30]
atuple = ('bob', 'tom', 'alice')
adict = {'name': 'john', 'age': 23}
for ch in astr:
print(ch)
for i in alist:
print(i)
for name in atuple:
print(name)
for key in adict:
print('%s: %s' % (key, adict[key]))
24-range用法及數字累加
# range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>> list(range(10))
# range(6, 11) # [6, 7, 8, 9, 10]
# range(1, 10, 2) # [1, 3, 5, 7, 9]
# range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
sum100 = 0
for i in range(1, 101):
sum100 += i
print(sum100)
25-串列實作斐波那契數列
串列中先給定兩個數字,后面的數字總是前兩個數字之和,
fib = [0, 1]
for i in range(8):
fib.append(fib[-1] + fib[-2])
print(fib)
26-九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print('%s*%s=%s' % (j, i, i * j), end=' ')
print()
# i=1 ->j: [1]
# i=2 ->j: [1,2]
# i=3 ->j: [1,2,3]
#由用戶指定相乘到多少
n = int(input('number: '))
for i in range(1, n + 1):
for j in range(1, i + 1):
print('%s*%s=%s' % (j, i, i * j), end=' ')
print()
27-逐步實作串列決議
# 10+5的結果放到串列中
[10 + 5]
# 10+5這個運算式計算10次
[10 + 5 for i in range(10)]
# 10+i的i來自于回圈
[10 + i for i in range(10)]
[10 + i for i in range(1, 11)]
# 通過if過濾,滿足if條件的才參與10+i的運算
[10 + i for i in range(1, 11) if i % 2 == 1]
[10 + i for i in range(1, 11) if i % 2]
# 生成IP地址串列
['192.168.1.%s' % i for i in range(1, 255)]
28-三局兩勝的石頭剪刀布
import random
all_choices = ['石頭', '剪刀', '布']
win_list = [['石頭', '剪刀'], ['剪刀', '布'], ['布', '石頭']]
prompt = """(0) 石頭
(1) 剪刀
(2) 布
請選擇(0/1/2): """
cwin = 0
pwin = 0
while cwin < 2 and pwin < 2:
computer = random.choice(all_choices)
ind = int(input(prompt))
player = all_choices[ind]
print("Your choice: %s, Computer's choice: %s" % (player, computer))
if player == computer:
print('\033[32;1m平局\033[0m')
elif [player, computer] in win_list:
pwin += 1
print('\033[31;1mYou WIN!!!\033[0m')
else:
cwin += 1
print('\033[31;1mYou LOSE!!!\033[0m')
29-檔案物件基礎操作
# 檔案操作的三個步驟:打開、讀寫、關閉
# cp /etc/passwd /tmp
f = open('/tmp/passwd') # 默認以r的方式打開純文本檔案
data = https://www.cnblogs.com/Mrzhangzong/archive/2020/10/09/f.read() # read()把所有內容讀取出來
print(data)
data = f.read() # 隨著讀寫的進行,檔案指標向后移動,
# 因為第一個f.read()已經把檔案指標移動到結尾了,所以再讀就沒有資料了
# 所以data是空字串
f.close()
f = open('/tmp/passwd')
data = https://www.cnblogs.com/Mrzhangzong/archive/2020/10/09/f.read(4) # 讀4位元組
f.readline() # 讀到換行符/n結束
f.readlines() # 把每一行資料讀出來放到串列中
f.close()
################################
f = open('/tmp/passwd')
for line in f:
print(line, end='')
f.close()
##############################
f = open('圖片地址', 'rb') # 打開非文本檔案要加引數b
f.read(4096)
f.close()
##################################
f = open('/tmp/myfile', 'w') # 'w'打開檔案,如果檔案不存在則創建
f.write('hello world!\n')
f.flush() # 立即將快取中的資料同步到磁盤
f.writelines(['2nd line.\n', 'new line.\n'])
f.close() # 關閉檔案的時候,資料保存到磁盤
##############################
with open('/tmp/passwd') as f:
print(f.readline())
#########################
f = open('/tmp/passwd')
f.tell() # 查看檔案指標的位置
f.readline()
f.tell()
f.seek(0, 0) # 第一個數字是偏移量,第2位是數字是相對位置,
# 相對位置0表示開頭,1表示當前,2表示結尾
f.tell()
f.close()
30-拷貝檔案
拷貝檔案就是以r的方式打開源檔案,以w的方式打開目標檔案,將源檔案資料讀出后,寫到目標檔案,
以下是【不推薦】的方式,但是可以作業:這里免費送大家一套2020最新python入門到高級專案實戰視頻教程,可以去小編的Python交流.扣扣.裙 :879151479,還可以跟行業大牛交流討教!
f1 = open('/bin/ls', 'rb')
f2 = open('/root/ls', 'wb')
data = https://www.cnblogs.com/Mrzhangzong/archive/2020/10/09/f1.read()
f2.write(data)
f1.close()
f2.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/165075.html
標籤:其他
上一篇:單例模式
