1. 程式人生 > 其它 >python程式設計:從入門到實踐 (第一版) 第七章學習筆記

python程式設計:從入門到實踐 (第一版) 第七章學習筆記

技術標籤:python基礎python

第7章:使用者輸入和while 迴圈

input()

prompt = "If you tell us who you are, we can personlize the message you see."
prompt += "\nWhat is your first name?"

name = input(prompt)
print("Hello, " + name + "!")

注意: 通過input() 輸入的值,預設為字串型別

>>> age = input("How old are you?")
How old are you?20
>>> age
'20'
>>> age > 18
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'

可以使用int() 函式,將字串型別的值轉為數值型

>>> age = input("How old are you?")
How old are you?20
>>> age = int(age)
>>> age > 18
True

判斷輸入數值的奇偶

number = input("Enter a number,and I'll tell you if it's even or odd:")
number = int(number)

if number % 2 == 0:
    print
("The number " + str(number) + " is even!") else: print("The number " + str(number) + " is odd!")

while 迴圈

示例
count = 1
while count <= 5:
    print(count)
    count += 1

輸出:

1
2
3
4
5

可使用while 迴圈讓程式在使用者願意時不斷地執行,如下面的程式parrot.py所示。我們在其中定義了一個退出值,只要使用者輸入的不是這個值,程式就接著執行:

parrot.py

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)
使用標誌
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)
使用break 退出迴圈

要立即退出while 迴圈,不再執行迴圈中餘下的程式碼,也不管條件測試的結果如何,可使用break 語句

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "

while True:
    city = input(prompt)
    if city == 'quit':
        break
    else:
        print("I'd love to go to " + city.title() + " again.")
在迴圈中使用continue

要返回到迴圈開頭,並根據條件測試結果決定是否繼續執行迴圈,可使用continue 語句。(僅跳出單次迴圈)
示例:從1-10,只打印其中的偶數

# 我寫的屎程式碼
number = 1
while number < 11:
    if number % 2 == 0:
        number += 1
        continue
    else:
        print(number)
        number += 1
# 書中程式碼
number = 0
while number < 10:
	number += 1
	if number % 2 == 0:
		continue
	print(number)

使用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())
刪除包含特定值的所有列表元素
test_list = ['ttt', 'abc', 'def', 'ghi', 'ttt', 'kkk', 'ttt']
print(test_list)
while 'ttt' in test_list:
    test_list.remove('ttt')
print(test_list)
使用使用者輸入來填充字典

可使用while迴圈提示使用者輸入任意數量的資訊。下面來建立一個調查程式,其中的迴圈每次執行時都提示輸入被調查者的名字和回答。我們將收集的資料儲存在一個字典中,以便將回答同被調查者關聯起來

responses = {}

#設定一個標誌,指出調查是否繼續
active = True
while active:
    name = input("\nHello, what's your name?")
    response = input("Which mountain would you like to climb?")
    #將姓名和反饋儲存到字典中
    responses[name] = response
    again = input("Would you like to let another person respond? (yes/ no) ")
    if again == 'no':
        active = False
for n, r in responses.items():
    print(n.title() + " would like to climb the " + r.title())

習題

7-1
car = input("Which car do you want to rent?")
print("Let me see if I can find you a " + car.title() + ".")
7-2
persons = input("How many people?")
persons = int(persons)
if persons > 8:
    print("We don't have  available talbe for " + str(persons) + ".")
else:
    print("We have  available table.")
7-3
number = input("Please enter a number: ")
number = int(number)
if number % 10 == 0:
    print(str(number) + " 是10的倍數。")
else:
    print(str(number) + " 不是10的倍數。")
7-4
prompt = "\n請輸入一系列披薩配料:"
prompt += "\n輸入'quit'退出程式。"
message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print("我們會在披薩中新增" + message + "。")
7-5
age = input("How old are you?")
age = int(age)
if age < 3:
    price = 0
elif age < 12:
    price = 10
elif age >= 12:
    price = 15
print("You need pay for " + str(price) + "$.")
7-6

以7-4為例,7-4即為題目要求的第一種做法

#第二種做法
prompt = "\n請輸入一系列披薩配料:"
prompt += "\n輸入'quit'退出程式。"
active = True
while active:
    message = input(prompt)
    if message != 'quit':
        print("我們會在披薩中新增" + message + "。")
    else:
        active = False
#第三種做法
prompt = "\n請輸入一系列披薩配料:"
prompt += "\n輸入'quit'退出程式。"
while True:
    message = input(prompt)
    if message != 'quit':
        print("我們會在披薩中新增" + message + "。")
    else:
        break
7-7
number = 1
while number < 10:
	print(number)
7-8
sandwich_orders = ['雞肉三明治', '火腿三明治', '素食三明治', '五香菸薰牛肉']
finished_sandwich = []
while sandwich_orders:
    finished = sandwich_orders.pop()
    print(finished + "已經做好了!")
    finished_sandwich.append(finished)
print("=================\n所有三明治訂單已經完成:")
for sandwich in finished_sandwich:
    print(sandwich)
7-9
sandwich_orders = ['雞肉三明治', '火腿三明治', '素食三明治', '五香菸薰牛肉', '五香菸薰牛肉', '五香菸薰牛肉']
finished_sandwich = []
print("店裡的五香菸薰牛肉已經賣完了")
while '五香菸薰牛肉' in sandwich_orders:
    sandwich_orders.remove('五香菸薰牛肉')
while sandwich_orders:
    finished = sandwich_orders.pop()
    print(finished + "已經做好了!")
    finished_sandwich.append(finished)
if '五香菸薰牛肉' not in finished_sandwich:
    print("已完成的訂單中沒有五香菸薰牛肉")
print("=================\n已完成的三明治訂單:")
for sandwich in finished_sandwich:
    print(sandwich)
7-10
# 使用使用者輸入填充字典