lnnk 2021-02-14 16:38 采纳率: 100%
浏览 65
已采纳

python,初学,小问题,求解

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 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 + ".")

书中的案例,在 #看看是否有人参与的 代码处输入非‘yes’or‘no’的回答,也会当成是’yes‘继续运行。

我希望能改成:

①用户输入非‘yes’or‘no’的回答时,程序可以提示用户‘您输入的格式不对,请重新输入。’

②让程序返回到responses[name] = response的后面继续提示用户输入‘yes’or‘no’(此处不可以打印调查结果)

改了很多次都不行,能力有限,希望各位可以帮忙。(尽量简单一些,)

谢谢

  • 写回答

1条回答 默认 最新

  • ProfSnail 2021-02-14 16:59
    关注

    while循环就行了。好说。

     

    while polling_active: 
        # 提示输入被调查者的名字和回答
        name = input("\nWhat is your name? ")
        response = input("Which mountain would you like to climb someday? ")
        
        # 将答卷存储在字典中
        responses[name] = response
        
        # 看看是否还有人要参与调查
        while True:
            repeat = input("Would you like to let another person respond? (yes/ no) ")
            if repeat == 'no':
                polling_active = False
                break
            elif repeat == 'yes':
                break
            else:
                print("Wrong input format. do it again.")
                continue
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失