Python小辣鸡的逆袭第七章之用户输入和while循环

第七章 用户输入和while循环

7.1 函数input()工作原理

    注意类型转换,input()函数输入类型都是字符串,要想进行数字比较,用int()

7.2 while循环

    熟练使用标记会简化代码

eg:

active=True
while active:
    topping=input()

    if topping =='quit':
        active=False #改变标记
    else :
        print("We while add" + topping + "into your pizza")
 

7.3 使用while循环来处理列表和字典

7.3.1 在列表之间移动元素

eg:

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())

结果:
verifying user:Candace
verifying user:Brian
verifying user:Alice

The following users have been confirmed:
Candace
Brian
Alice

7.3.2 删除包含特定值的所有列表元素

eg:

pets=['cat','dog','cat','fish','rabbit','cat']
print(pets)

while 'cat' in pets:#判断当前列表是否还有未删除的'cat'
    pets.remove('cat')

print(pets)

7.3.3 使用用户输入来填充字典

eg:

responses={}
#设置标记
polling_active=True

while polling_active:
    name=input("\nWhat's your name?")
    response=input("Which moutain would you like to climb someday?")
    #将受访者和回答存入字典中
    responses[name]=response
    #判断是否还有受访人
    repeat=input("Would you like to let another person respond?(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+' '+"someday!")
结果:

What's your name?Eric
Which moutain would you like to climb someday?Denali
Would you like to let another person respond?(yes/no)yes

What's your name?Lynn
Which moutain would you like to climb someday?Devil's Thumb
Would you like to let another person respond?(yes/no)no

---Poll Results---
Lynnwould like to climb Devil's Thumb someday!
Ericwould like to climb Denali someday!

猜你喜欢

转载自blog.csdn.net/weixin_42404145/article/details/80642897