天天看點

Python chapter 7 learning notes

版權聲明:本文為部落客原創文章,原文均發表自http://www.yushuai.me。未經允許,禁止轉載。 https://blog.csdn.net/davidcheungchina/article/details/78243686

函數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 + ".")