1.字符
str=‘sweet’
str.upper() 字符全大寫 SWEET
str.title() 字符首字母大寫 Sweet
str.lower() 字符全小寫 sweet
2.if條件判斷
(1)if a==b or/and c!=d 方式
(2)if a in/notin list1 方式
舉例如下:
banned_users = ['andrew', 'carolina', 'david']user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
結果:Marie, you can post a response if you wish.
(3)if-elif-else
(4)list=[]列表為空,if list 返回False
3.用戶輸入和while循環
3.1 函數input()的工作原理
函數input() 讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入后,Python將其存儲在一個變量中,以方便你使用
。
message = input("Tell me something, and I will repeat it back to you: “)
print(message)
結果:
Tell me something, and I will repeat it back to you: Hello everyone! 提示信息后,輸入Hello everyone!后,輸入存入message
Hello everyone! 打印message的值
3.2使用int()來獲取數值輸入
舉例:
age = input("How old are you? “)
How old are you? 21
age = int(age)
age >= 18
True
3.3求模運算符 %
求模運算符(%)是一個很有用的工具,將兩個數相除並返回余數。
3.4while循環
(1)用法舉例:
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
(2)使用break退出循環
break 立即退出循環,不再執行循環余下的代碼。
(3)在循環中使用continue
continue 會返回到循環開頭,並根據條件測試結果決定是否繼續執行循環,不會像break那樣直接退出整個循環,只會跳出當前執行的那一條。
(4)使用while循環來處理列表和字典
一種辦法是使用一個while 循環,在驗證用戶的同時將其從未驗證用戶列表中提取出來,再將其加入到另一個已驗證用戶列表中。舉例如下:
# 首先,創建一個待驗證用戶列表
# 和一個用於存儲已驗證用戶的空列表
unconfirmed_users = ['alice', 'brian', 'candace’]
confirmed_users = []
# 驗證每個用戶,直到沒有未驗證用戶為止
# 將每個經過驗證的列表都移到已驗證用戶列表中
while unconfirmed_users:(直到這個列表所有值循環玩停止)
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# 顯示所有已驗證的用戶
print("\nThe following users have been confirmed:”)
for confirmed_user in confirmed_users:
print(confirmed_user.title())
(5)刪除包含特定值的所有列元素
舉例:
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat’]
print(pets)
while 'cat' in pets:
pets.remove('cat’)
(6)使用用戶輸入來填充字典
舉例如下:
responses = {}
# 設置一個標志,指出調查是否繼續
polling_active = True
while polling_active:
# 提示輸入被調查者的名字和回答
name = input("\nWhat is your name? “)
response = input("Which mountain would you like to climb someday? “)
# 將答卷存儲在字典中
responses[name] = response
# 看看是否還有人要參與調查
repeat = input("Would you like to let another person respond? (yes/ no) “)
if repeat == 'no’:
polling_active = False
# 調查結束,顯示結果
print("\n--- Poll Results —")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
結果:
What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes
What is