python如何循环使用input_python – while循环检查有效的用户输入?

参见英文答案 > Asking the user for input until they give a valid response                                    17个

Python新手在这里很抱歉我确定这是一个愚蠢的问题,但我似乎无法在一个教程中解决以下挑战,该教程要求我使用while循环来检查有效的用户输入.

(使用Python2.7)

这是我的代码,但它无法正常工作:

choice = raw_input('Enjoying the course? (y/n)')

student_surveyPromptOn = True

while student_surveyPromptOn:

if choice != raw_input('Enjoying the course? (y/n)'):

print("Sorry, I didn't catch that. Enter again: ")

else:

student_surveyPromptOn = False

以上打印到控制台:

Enjoying the course? (y/n) y

Enjoying the course? (y/n) n

Sorry, I didn't catch that. Enter again:

Enjoying the course? (y/n) x

Sorry, I didn't catch that. Enter again:

Enjoying the course? (y/n)

这显然是不正确的 – 当用户输入’y’或’n’时循环应该结束但我不知道如何做到这一点.我在这做错了什么?

注意:挑战要求我同时使用!=运算符和loop_condition

解决方法:

更短的解决方案

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 = True

while 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) y

choice = y

Enjoying the course? (y/n) n

choice = y

input = n

Sorry, I didn't catch that. Enter again:

Enjoying the course? (y/n) x

choice = y

input = x

Sorry, I didn't catch that. Enter again:

Enjoying the course? (y/n)

正如您所看到的,代码中的第一步是出现问题并且您的答案初始化了选择的值.这就是你做错了.

使用!=和loop_condition的解决方案

如果你必须使用!=运算符和loop_condition,那么你应该编码:

student_surveyPromptOn = True

while 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​​的解决方案和我更短的解决方案都更优雅(即更加pythonic).

标签:python,while-loop,user-input

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值