函數input()工作原理
n 示例演示了一種創建多行字符串的方式,第一行將消息的前半部分存儲在變量prompt中,第二行,+=在存儲在prompt中的字符串末尾附件一個字符串。
例如:
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt +="\nWhat is your first name?\n"
n 在使用時如果輸入數字,系統將自動將其轉換爲字符串。如果想仍作爲數字使用,可以將其強制轉換爲數字,例如整數可以用int()。
l while循環
n 在循環中使用continue,可以繼續執行循環,它不會像break語句那樣不再執行餘下的代碼並退出整個循環,而是重新開始這個循環。
n 避免無限循環:如果程序陷入無限循環,可按Ctrl+C,也可以關閉顯示程序輸出的終端窗口(不適用於Sublime Text)
l 使用while循環來處理列表和字典
n 在列表之間移動元素
n 刪除包含特定值的所有列表元素
n 使用用戶輸入來填充字典
# -*- coding: utf-8 -*-
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 respod?(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 + ".")