7.1、函數input()
用int()将輸入轉換成整型
求模運算符:%,用于兩數相除傳回餘數。eg. 100%10=0
練習:
# coding=GBK
#7-1
car=input('What car do you wanna rent?')
print('Let me see if I can find you a Subaru' )
#7-2
people=input('How many peole eat?')
people=int(people)
if people > 8:
print('There is no empty table.')
else:
print('Free table')
#7-3
number=input('Enter a number,and I will tell if it is a multiple of 10 ')
number=int(number)
if number%10 == 0:
print('It is a multiple of 10')
else:
print("It isn't")
7.2 while 循環
while循環不斷運作。當指定條件不滿足時,退出循環。
使用标志用于判斷程式是否處于活動狀态。True運作,False結束。
用break退出循環。
用continue結束此次循環,進入下次循環。
務必對每個While循環進行測試,以免進入無限循環。當進入無限循環時,按Ctrl+C退出或關閉視窗。
相關練習
#7-4
print('Please add your ingredient: ')
a=''
while a != 'quit':
a=input()
if a != 'quit':
print('We will add '+a)
else:
print('Please wait a minute')
#7-5 and 7-6
prompt='Please enter your age: '
prompt+='\ninput quit to exit.'
active=True
while active:
age=input(prompt)
if age=='quit':
break
else:
if int(age) < 3:
print('Free')
elif int(age) <= 12:
print('Please pay $10.')
else:
print('Please pay $15.')
7.3 用while處理清單和字典
在清單間移動元素:
練習:
#7-8、7-9
解一:
sandwich_orders=['A','pastrami','C','pastrami','E','pastrami']
print('Pastrami is sold out')
finished_sandwich=[]
b=0
while b < len(sandwich_orders):
a=sandwich_orders[b]
if a.lower() == 'pastrami':
b=b+1
continue
else:
finished_sandwich.append(a)
print('I made your '+a)
b=b+1
print(finished_sandwich)
删除清單内的特定值:
#7-9
sandwich_orders=['A','pastrami','C','pastrami','E','pastrami']
print('Pastrami is sold out')
finished_sandwich=[]
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
finished_sandwich=sandwich_orders
print(finished_sandwich)
使用使用者輸入填充字典:
7-10
#coding=GBK
places={}
active=True
while active:
name=input('姓名:')
place=input('夢想的度假勝地:')
places[name]=place
repeat=input('還有人要回答嗎?(yes/no)')
if repeat.lower() =='no':
active=False
print('調查結果')
for name,place in places.items():
print(name+'想去'+place+'.')