栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

While循环以检查有效的用户输入?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

While循环以检查有效的用户输入?

较短的解决方案

while raw_input("Enjoying the course? (y/n) ") not in ('y', 'n'):    print("Sorry, I didn't catch that. Enter again:")

您的代码在做什么错

关于您的代码,您可以添加一些打印内容,如下所示:

choice = raw_input("Enjoying the course? (y/n) ")print("choice = " + choice)student_surveypromptOn = Truewhile student_surveypromptOn:    input = raw_input("Enjoying the course? (y/n) ")    print("input = " + input)    if choice != input:        print("Sorry, I didn't catch that. Enter again:")    else:        student_surveypromptOn = False

上面打印出:

Enjoying the course? (y/n) ychoice = yEnjoying the course? (y/n) nchoice = yinput = nSorry, I didn't catch that. Enter again:Enjoying the course? (y/n) xchoice = yinput = xSorry, I didn't catch that. Enter again:Enjoying the course? (y/n)

如您所见,代码中的第一步是出现问题,答案将初始化的值

choice
。这就是你做错了。

一个解决方案
!=
,并
loop_condition

如果必须同时使用

!=
运算符和,
loop_condition
则应编写代码:

student_surveypromptOn = Truewhile student_surveypromptOn:    choice = raw_input("Enjoying the course? (y/n) ")    if choice != 'y' and choice != 'n':        print("Sorry, I didn't catch that. Enter again:")    else:        student_surveypromptOn = False

但是,在我看来,Cyber​​的解决方案和我较短的解决方案都更优雅(例如,更Python化)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660576.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号