Python学习打卡:while循环退出程序、列表间元素移动、删除特定值以及字典填充

仍然是一个门外汉记的笔记~

 1、使用while循环退出程序:不同价格的输出if()语句:

#电影票:3岁以下免费,3-12岁10美元,12以上15美元,循环询问年龄,指出票价
prompt = "\nEnter 'quit' to close."
prompt += "\nInput your age:"
message = ""
while message != 'quit':
    age = input(prompt)
    if age != 'quit':
        age = int(age)
        if age <= 3:
            price = 0
        elif 3 < age <= 12:
            price = 10
        else:
            price = 15
        print(f"Your price is ${price}")
    else:
        break

2、 列表间移动元素

#建立两个字典,一个字典为未认证的用户,一个为已经认证的用户
confirmed_users = []
unconfirmed_users = ['didi', 'mimi', 'hihi']
#使用while循环将三个人转移
while unconfirmed_users:
    current_users = unconfirmed_users.pop()
    confirmed_users.append(current_users)
    print(f"Varify the user: {current_users.title()}")
print(f"\nConfirmed users are:")
print(confirmed_users)
#使用for循环将人名全部输出
for user in confirmed_users:
    print(f"\t{user}")

 3、删除列表中的特定值:删除重复元素的值

#删除列表中的特定值
pets = ['cat', 'dog', 'fish', 'cat', 'dog']
#删除全部的cat
while 'cat' in pets:
    pets.remove('cat')
    print(pets)
print(pets)

4、填充字典:使用input的键值对,填充字典

#使用用户填充字典
users = {}
prompt_1 = "\nPlease enter your name: "
prompt_2 = "\nPlease enter your age: "
prompt_3 = "\nDo you want to quit the program?"
prompt_3 += "\nYes or no:"
active = True
while active:
    user_name = input(prompt_1)
    user_age = input(prompt_2)
    #将用户信息存入字典
    users[user_name ] = user_age
    answer = input(prompt_3)
    if answer == 'yes':
        active = False
print(users)
for m, n in users.items():
    print(f"\n{m.title()}'s age is {n}.")

5、一个填充字典的练习: 通过用户输入,收集姓名以及喜欢的地点,存为字典,检索检验

#度假胜地:创建字典储存调查结果
resorts = {}
q1 = "\nPlease input your name: "
q2 = "What's your ideal vacation spot? "
q3 = "Have you finished? "
active = True
while active:
    students = input(q1)
    answers = input(q2)
    confirm = input(q3)
    resorts[students] = answers
    if confirm == 'yes':
        active = False
    print(f"{students.title()}'s favorite place is {answers.title()}!")
for x, y in resorts.items():
    print(f"\n{x.title()}'s favorite place is {y.title()}!")
for x in resorts.keys():
    print(f"\t{x.title()}")

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值