【问题标题】:In Python, How do I make my conditional if loop not execute if input is valid?在 Python 中,如果输入有效,如何使条件 if 循环不执行?
【发布时间】:2016-10-31 13:20:42
【问题描述】:
#Write a short program that will do the following
#Set a value your favorite number between 0 and 100
#Ask the user to guess your favorite number between 0 and 100
#Repeat until they guess that number and tell them how many tries it took
#If the value they guessed is not between 0 and 100
#tell the user invalid guess and do not count that as an attempt

我的问题是,即使用户猜到了 0 到 100 之间的数字,它仍然会打印出“猜错。再试一次”。如果输入可接受(1-100),我如何控制我的循环跳过打印语句和问题重复?提前致谢!

favoriteNumber = 7
attempts = 0

guess = raw_input("Guess a number between 0 and 100: ")

if (guess  < 0) or (guess > 100):
    print "Invalid guess. Try again"
    guess = raw_input("Guess a number between 0 and 100: ")

attempts1 = str(attempts)
print "it took " + attempts1 + "attempts."

【问题讨论】:

  • 什么循环?您的代码中没有任何循环。

标签: python validation loops input


【解决方案1】:

使用输入而不是raw_input,所以你得到的是整数而不是字符串

favoriteNumber = 7
attempts = 0


while True:
    guess = input("Guess a number between 0 and 100: ")
    if (guess  < 0) or (guess > 100):

        attempts=attempts+1
        print "Invalid guess. Try again"
    else:
        attempts=attempts+1
        break

attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."

【讨论】:

  • 非常感谢大家,但您对我的帮助最大。
【解决方案2】:

您的 raw_input 返回一个字符串,该字符串始终为 &gt; 100。将其转换为带有 int(raw_input()) 的数字

【讨论】:

    【解决方案3】:

    在 Python 2.7.10 中,如果您不将字符串转换为整数,它似乎会接受它,但适用于数字的所有规则都返回 false。 这是一个工作示例:

    favoriteNumber = 7
    attempts = 0
    
    guess = raw_input("Guess a number between 0 and 100: ")
    
    if (int(guess)  < 0) or (int(guess) > 100):
        print "Invalid guess. Try again"
        guess = raw_input("Guess a number between 0 and 100: ")
    
    attempts1 = str(attempts)
    print "it took " + attempts1 + " attempts."
    

    在 Python 3.4 中,原始代码会产生一个错误,告诉您它是字符串而不是整数。但是,就像 Paul 所说,您可以将 raw_input 放在 int() 命令中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多