時間:2018/04/28
主要內容:
用戶輸入和while循環
函數input()的工作原理
使用int()來獲取整數值
age=int(input('Your age is: '))
print(age+15)
求模運算符
%:兩數相除返回餘數
number = int(input('Enter a number,and I\'tell you if it\'s even or odd: '))
if number % 2 == 0:
print('\nThe number '+str(number)+' is even.')
else:
print('\nThe number '+str(number)+' is odd.')
while循環
if&while 差別:while循環語句,可以執行多次,if是條件語句,只是單次執行。
使用while循環
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1#該處爲代碼current_ number = current_number + 1 的簡寫
讓用戶選擇何時退出
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.'
message = ' '
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
我們將變量active設成True,讓程序最初處於活動狀態。簡化了while語句,因爲不需要在其中做任何比較--相關邏輯判斷由程序的其他部分處理。
使用break退出循環
立即退出循環,不再運行循環中剩餘的代碼。
prompt = '\nPlease enter the name of a city you have visited: '
prompt += '\nEnter \'quit\' when you finish are finished.'
while True:#以while ture打頭的循環將不斷運行,直到遇見break語句
city = input(prompt)
if city == 'quit':
break
else:
print('I\'d love to go to '+city.title()+'!')
!在任何循環中都可以使用break語句,比如python中的使用break退出遍歷列表或者字典的for循環。
在循環中使用continue
要返回到循環開頭,並根據測試結果決定是否繼續執行循環,並不像break語句一樣不再執行餘下的代碼而退出整個循環。
#打印10以內的奇數
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
避免無限循環
使用while循環來處理列表和字典
for循環是一種遍歷列表的有效方式,但是for循環中不應該修改列表,否則將導致Python難以跟蹤其中的元素。要在遍歷列表的同時進行修改,可以使用while循環。
在列表中移動元素
將驗證用戶的同時將其從未驗證用戶列表中提取出來,再將其加入到另一個已驗證用戶列表中。
#首先,創建一個待驗證用戶列表
#和一個用於儲存已驗證用戶的空列表
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
#驗證每個用戶,至到沒有未驗證用戶爲止
#將每個經過驗證的列表都移到已驗證用戶的列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()#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)
刪除包括特定值的所有列表元素
remove.()方法僅能刪除列表中的第一個出現的該值的元素,利用while循環可以刪除該列表中的所有特定值。
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
使用用戶輸入來填充字典
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 response?(yes/no)')
if repeat == 'no':
polling_active = False
#調查結束,顯示結果
print('\n----Poll Result---')
for name,response in responses.items():
print(name + ' would like to climb ' + response + '.')