简体   繁体   English

需要更短/更好的python while循环解决方案

[英]Need shorter/more elegant solution to python while loop

I'm a new programmer and I was struggling with a solution to this problem: 我是一个新程序员,我一直在努力解决此问题:

User Input with Loops and Conditionals. 带循环和条件的用户输入。 Use raw_input() to prompt for a number between 1 and 100. If the input matches criteria, indicate so on the screen and exit. 使用raw_input()提示输入一个介于1到100之间的数字。如果输入符合条件,请在屏幕上进行指示并退出。 Otherwise, display an error and re-prompt the user until the correct input is received. 否则,显示错误并重新提示用户,直到收到正确的输入为止。

My last attempt finally worked but I'm interested to know your more elegant solutions, my memory appreciates all of your input :P 我的最后一次尝试终于成功了,但是我很想知道您更优雅的解决方案,我对您的所有投入表示感谢:P

n = int(input("Type a number between 1 and 100 inclusive: "))
if 1 <= n <= 100:
    print("Well done!" + " The number " + str(n) + " satisfies the condition.")
else:
    while (1 <= n <= 100) != True:
        print("Error!")
        n = int(input("Type a number between 1 and 100: "))
    else:
        print ("Thank goodness! I was running out of memory here!")

You can simplify the code, using a single loop: 您可以使用一个循环来简化代码:

while True:
    n = int(input("Type a number between 1 and 100 inclusive: "))
    if 1 <= n <= 100:
        print("Well done!" + " The number " + str(n) + " satisfies the condition.")
        print ("Thank goodness! I was running out of memory here!")
        break # if we are here n was in the range 1-100 
    print("Error!") # if we are here it was not

You just print the output and break if the user enters a correct number or print("Error!") will be printed and the user will be asked again. 您只需打印输出并break如果用户输入正确的数字或​​将print("Error!")并再次询问用户。

On a side note, if you are using python2, input is the equivalent to eval(raw_input()) , if you are taking user input you should generally use raw_input as per the instructions in your question. 附带说明一下,如果您使用的是python2,则输入等效于eval(raw_input()) ,如果您使用的是用户输入,则通常应按照问题中的说明使用raw_input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM