天天看點

python入門基礎之變量+清單+循環+字典

文章目錄

    • 【1】常用快捷鍵
    • 【2】引号
    • 【3】變量+字元串
    • 【4】if語句
    • 【5】邏輯運算符
    • 【6】while循環
    • 【7】字元清單
    • 【8】數字清單
    • 【9】字典

小白自用筆記如有錯誤還請見諒

首先将自己的python設定中文版、調整字号、設定背景等等

【1】常用快捷鍵

運作: Shift+Ctrl+F10

重新運作: Ctrl+F5

傳回上一步:Ctrl+z

重構: Shift+F6 可将所有名字為name1的換成name2

光标移動到最左/右: Fn+左/右

光标向左/右移動一位:Ctrl+左/右

光标向左/右選中一格單詞:Ctrl+Shift+左/右

光标選中一行:Ctrl+Alt+T

調出表情符: Win + ;

删除單個單詞: Ctrl + 删除

光标不動實作換行: Ctrl + 換行

檢視某函數源碼: Ctrl+B

(在pycharm中把滑鼠定位到這個函數,然後用快捷鍵去檢視)

更多參考

https://blog.csdn.net/yuanqimiao/article/details/106308121(https://blog.csdn.net/cuomer/article/details/81534140)

【2】引号

'''
(1)三個單引号有多行注釋的作用
(2)#是單行注釋
(3)' 和 "靈活使用能讓句子中的’s更清晰
(4)在字元串指派時可以多行指派
'''
message = '''Hello World:
What a wonderful day!
Dosen't it?'''
'''輸出為:
Hello World:
What a wonderful day!
Dosen't it?
'''

message = 'Hello'\
          ' world'
#輸出為Hello world
           

【3】變量+字元串

變量

python 3 math module見下連結

https://docs.python.org/3/library/math.html

message = '  Liu yuhang ' # 也可使用" "
# \t \n、強行轉換、+ - * / +=、> < >= <= ==等與c相同 **為幂(**  >  * = /   > +=- )
# 10//3 = 3
# 10/3 =3.333333
#數字相關的函數
import math
print(round(2.9))  #四舍五入函數
print(abs(-2.9))  #絕對值函數
print(math.ceil(2.7)) #取大
print(math.floor(2.7)) #取小etc
           

字元串

replace使用時

【1】原有字元串調用修改後原有字元串沒有修改,而是傳回值進行了修改,需要設定變量進行儲存,展現了字元串是不可變類型資料(清單或者字典就是可變類型)

【2】替換次數省略後預設是所有都替換

【3】替換次數大于存在次數,是将所有都替換

length = len(message) #擷取message的長度

print(message.capitalize()) #字元串的第一個字母大寫
print(message.title()) #開頭字母大寫
print(message.upper()) #所有字母大寫
print(message.lower()) #所有字母小寫
print(message.strip()) #首尾去掉空格
print(message.lstrip()) #去掉左空格
print(message.rstrip()) #去掉右空格

new_str = message.ljust(10,'*') #共10位,左對齊,*補空
new_str = message.rjust(10,'*') #共10位,右對齊,*補空
new_str = message.center(10,'*') #共10位,中間對齊,*補空

position = message.find('y')
 #傳回第一次出現y的位置
# position = message.find('yuhang') 傳回yuhang首字母出現的位置
print('Liu' in message)
 #若Liu存在傳回message則傳回True,否則傳回False
print(message.replace('i','aa')) #用aa替換i,message.replace('i','aa',1)再列印message則無變化

first = 'jonhn'
second = 'smith'
name = f'{first} [{second}] is a coder' 
print(name)# ==> jonhn [smith] is a coder
           

判斷真假

【1】是否以特定字元串開頭/結尾,stratswith() / endswith() 是傳回True,否則傳回False

str = 'hello, my dear'
print(str.startswith('hello'))
print(str.endswith('dear'))
           

【2】isalpha():如果字元串至少一個字元并且所有字元都是字母則傳回True,否則False

【3】isdigit():如果字元串至少一個字元并且所有字元都是數字則傳回True,否則False

【4】isalnum():如果字元串至少一個字元并且所有字元都是字母或數字則傳回True,否則False

(即【3】和【4】的并集)

str = 'hello my dear'
print(str.isalpha())#傳回False
str = 'hellomydear'
print(str.isalpha())#傳回True

str = 'hello my dear1'
print(str.isdigit()) #傳回False
str = '12345'
print(str.isdigit())#傳回True

str = 'hello1my3dear*'
print(str.isalnum()) #傳回False
str = 'hello1my3dear'
print(str.isalnum()) #傳回True
           

【5】isspace():如果字元串中隻包括空白,則傳回True否則傳回False

str = '   ** '
print(str.isspace()) #傳回False
str = '    '
print(str.isspace()) #傳回True
           

【4】if語句

is_hot = True
is_cold = False
if is_hot:
    print("It's a hot day")
    print("Drink plenty of water")
elif is_cold:
    print("It's a cold day")
    print("Wear warm clothes")
else:
    print("It's alovely day")
print("Enjoy your day")

#小習題,實作将英鎊和千克的轉化
weight =int(input("weight: ")) #input 傳回str類型
choice = input("(L)bs or (K)g:")
if choice.title() == 'L':
    last = weight * 0.45
    print(f'you are {last} kilos')
elif choice.title() == 'K':
    last = weight /  0.45
    print(f'you are {last} pounds')
           

【5】邏輯運算符

has_high_income = True
has_good_credit = False
if has_good_credit and has_high_income:
    print("邏輯與")
elif has_good_credit or has_high_income:
    print("邏輯或")
elif has_good_credit and not has_high_income:
    print("邏輯非")
           

【6】while循環

#習題:三次以内猜數
import random
correct_num = random.randint(0,9)
guess_count = 1
guess_max = 3
while guess_count <= guess_max:
    x = int(input("Guess:"))
    if x == correct_num:
        print("You Win!")
        break
    else:
        if guess_count >= 3:
           print("You Lose")
           break
        guess_count += 1
        
#習題:列印九九乘法表
x = y = 1
while x<10:
    y = 1
    while y <= x:
        print(f'{y}*{x}={x*y}',end=" ")
        y+=1
    print()#print('')會多一行空行
    x+=1 
           

while-else語句

示例1:

i=1
while i<=3 :
    print("* ")
    i+=1
else:
    print("while-else 結束")
#while循環結束後執行else部分與直接print("while-else 結束")作用一樣       
           

示例2:

如果while中有break則不會執行else後的語句,但如為else則會執行else後的語句

i=1
while i<=3 :
    print("* ")
    i+=1
    if i==2:
        print("while-else 提前結束")
        break
else:
    print("while-else 結束")
           

【7】字元清單

通路

根據下标通路或者周遊

lovely_day = ['WakeUp','reading','breakfast','studying','etc']
#通路
print(lovely_day[0]) #列印下标為0的元素
print(lovely_day[-2]) #列印倒數第二個元素
for x in lovely_day:
    print(x)
           

查找

in,find,count,index同樣适用于字元串

lovely_day = ['WakeUp','reading','breakfast','studying','etc']

n = len(lovely_day) #求清單元素個數
print('etc' in lovely_day)
 #檢查etc是否在清單裡,在傳回True否則False
 print('etc' not in lovely_day)
 #檢查etc是否不在清單裡,不在傳回True否則False
 
n = lovely_day.count('reading')
 #查清單中reading出現的次數,不存在為0
 
print(lovely_day.index('studying'))
 #從左找studying 的首字母的下标,不存在報錯
 #rindex() : 與index一緻,從右向左查找 不存在報錯
 
str = 'Hello my dear'
print(str.find("my", 0, len(str)))
 #從左找到my的第一個字母的下标
 #rfind():與find一樣差別是這個從右側開始查找
           

添加

【1】末尾添加,或者通過下标插入一個

lovely_day = ['WakeUp','reading','breakfast','studying','etc']

lovely_day.append('sleep')
 #在清單末尾加上元素sleep
 
lovely_day.insert(4,'sleep') 
 #在下标為4的前面加上sleep
           

【2】添加n個元素的方法

lovely_day = ['WakeUp','reading','breakfast','studying','etc']
n = int(input('請輸入添加元素數量:'))
i = 1
str =''
while i<=n:
    str = input(f'請輸入添加的第{i}個元素:')
    i+=1
    lovely_day.append(str)
print(lovely_day)
           

【3】添加一個序列的方法:extend()

lovely_day = ['WakeUp','reading','breakfast','studying','etc']
#把['a','bb','ccc']添加到清單後面
lovely_day.extend(['a','bb','ccc'])
print(lovely_day)

#把[ '1', '2', '3', '4']添加到清單後面
lovely_day.extend('1234')
print(lovely_day)
           

【3】複制清單:copy()

day2 = lovely_day[ : ]
 #将lovely_day的元素全部複制到day2,可以前後加範圍
 
day2 = lovely_day.copy()
 #将lovely_day的元素全部複制到day2
day2.append('sleep')
           

删除

del(lovely_day[1]) 
#删除元素

disapper = lovely_day.pop(2) 
#将lovely_day[2] 删除的同時将其賦給disapper,不加數字預設删除最後一個

lovely_day.remove('breakfast')
 #将第一個為breakfast的元素移除
 
lovely_day.clear() #清空清單
           

排序

lovely_day.sort()
 #按照字典排序 或用 lovely_day.sort(reverse=False) 
 
lovely_day.sort(reverse=True)
 #按照反字典排序
 
print(sorted(lovely_day))
 #臨時排序
 
lovely_day.reverse() 
#清單元素前後倒置
           

分割+合并

【1】分割split(分割字元串如‘my’,num):

将my兩邊分割開,num表示分割my的次數。如括号内不加變量,則将字元串的每個單詞分割成清單中的元素

str = 'hello my dear, my name is lyh'
new_str = str.split('my',2)
print(new_str)
           

【2】合并join(str):

将清單中的元素合并。合并後用‘ ’隔開

str = ['hello','my','dear']
new_str = ' '.join(str)
print(new_str)
           

【8】數字清單

(1)一維

number = [1,2,3,7,1,2]
x = min(number)
x = max(number)
x = sum(number)

for integer in range(0,11,2):
    print(integer)#列印1-10的偶數

squares = [value**2 for value in range(1,10) ]
#squares = [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(number[:3])  #列印number[0]到number[2]
print(number[-2:]) #列印倒數第二個到number[0]
for x in number[:3]:
    print(x)
           

(2)元組:即不可對元素修改的清單

多資料元組: unchange = (200,50)

單個資料元組:unchange = (200,)

元組不支援修改,支援查找如:index,count,len

unchange = ('a','bb','ccc','a')
print(unchange.index('ccc'))
print(unchange.count('a'))
print(len(unchange))
           

but 可以利用變量名進行修改

unchange = (200,50)
unchange =(200,2,1,50)
print(unchange)
           

(3)解壓(同樣适用于清單)

必須左邊的變量數=元素數

#解壓(同樣适用于清單)必須左邊的變量數=元素數
a,b,c,d = number
print(f'{a} {b} {c} {d}')
           

(4)二維(清單中的清單)

與C語言中的二維數組類似:第一個下标取行,第二個下标取列

number = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
]
for row in number: #周遊二維清單
    for y in row:
        print(y)
           

【9】字典

(1)建立字典

customer ={
    "name" : "lyh",
    "age" : 30,
    "sign_or_not" :True
}
#空字典
customer={}
customer=dict()
           

(2)字典基本操作

1.查

print(customer['name'])   
#輸出lyh

print(customer.keys())   
#輸出:dict_keys(['name', 'age', 'sign_or_not'])
#傳回可疊代的對象

print(customer.values()) 
#輸出:dict_values(['lyh', 30, True])
#查找字典中所有的value,傳回可疊代的對象

print(customer.items())
#輸出:dict_items([('name', 'lyh'), ('age', 30), ('sign_or_not', True)])
#
'''找字典中所有鍵值對,傳回所有可疊代對象
裡面的資料全是元組,元組資料1是字典的key
元組資料2是字典key對應的值
'''
           

2.增

print(customer.get("age")) 

print(customer.get("birdate","Jan 8 2001"))
#如果原來沒有birthdate則增加birthdate,并指派為Jan 8 2001

customer["birthdate"] = "Jan 8 2001"
#增加
print(customer["birthdate"])
           

3.修

customer["name"] = 'liu yuhang'
print(customer["name"])
           

4.删

del(customer["name"]) #删除鍵值對
customer.clear() #清空
           

5.周遊

周遊key

customer ={
    "name" : "lyh",
    "age" : 30,
    "sign_or_not" :True
}
for key in customer:
    print(key,end=' ')
           

周遊values

for key in customer:
    print(customer[key],end=' ')
#或    
for value in customer.values():
    print(value,end=' ')
#lyh 30 True 
           

周遊元素

for iterm in customer.items():
    print(iterm,end=' ')
#('name', 'lyh') ('age', 30) ('sign_or_not', True) 
           

周遊字典的鍵值對(拆包)

字典序列.items():傳回可疊代對象,内部是元組,元組是兩個資料,資料1是key,資料2是value

customer ={
    "name" : "lyh",
    "age" : 30,
    "sign_or_not" :True
}
for key,value in customer.items():
    print(f'key={key} value={value}',end=' ')
#key=name value=lyh key=age value=30 key=sign_or_not value=True
           

(2)習題:

1.将1234變為One Two Three Four

phone = input("Phone :")
change ={
    "1" : 'One',
    "2" : 'Two',
    "3" : 'Three',
    "4" : 'Four'
}
output = '' #一定要定義
for ch in phone:
    output += change.get(ch ,'!') +' '
    #如果get後面的ch不屬于字典則将!儲存到output
print(output)
           

2.實作以下效果

輸入:>I am sad :(
輸出:I am sad (╬▔皿▔)╯ 
           

代碼

message = input(">")
word = message.split(' ')
#可産生 word = ['I', 'am', 'sad',':(']的效果
emojs = {
    ":)" : 'o(*^@^*)o',
    ":(" : '(╬▔皿▔)╯'
}
out = ""
for x in word:
    out += emojs.get(x,x) + ' '
    #入果找到對應則替換否則不變
print(out)