需要将用户输入验证为整数

时间:2015-02-23 22:42:54

标签: python validation types

我想添加代码,以便在用户输入除整数之外的任何内容时,它会输出一些内容。在我写的最后一行 if guess != int我希望程序决定猜测是否不是数字。

import random

number = random.randint(1,100)
guess = 0
guesses = 0

while guess != number:

    guess = int(input("Guess my number between 1 and 100(inclusive):"))
    guesses = guesses + 1

    if guess == number:
        print("Well done! My number is:"number,"You had",guesses,"guesses"
    elif guess < number:
        print ('sorry, my number is higher')
    elif guess > number:
        print ('Sorry, My number is lower')
    if guess != int:
        print ("Enter a Number!!")

3 个答案:

答案 0 :(得分:4)

让我们使用好的旧EAFP

  

比获得许可更容易请求宽恕。这种常见的Python编码风格假设存在有效的键或属性,并且如果假设被证明是错误则捕获异常。这种干净和快速的风格的特点是存在许多try和except语句。该技术与许多其他语言(如C。

)共有的LBYL风格形成对比
guess = input("Guess my number between 1 and 100(inclusive):")
try:
    guess = int(guess)
except ValueError:
    print ("Enter a Number!!")
else:
    if guess == number:
        print("Well done! My number is:"number,"You had",guesses,"guesses"
    elif guess < number :`
        print ('sorry, my number is higher')
    else:
        print ('Sorry, My number is lower')

答案 1 :(得分:0)

在我被警告关于原始输入总是一个字符串之后。也许这就是你需要的东西

guess =int(input("Guess my number between 1 and 100(inclusive):"))
guesses = guesses + 1
try:
    guess = int(guess)
    if guess == number:
     print("Well done! My number is:", number,"You had",guesses,"guesses")
    elif guess < number :
       print ('sorry, my number is higher')
    elif guess > number:
        print ('Sorry, My number is lower')
except:
    print("Enter a number!")

请注意,您不在任何地方使用guesses,并且这不是循环,因此它只会重复一次,而且您也从未定义过您的号码。也许更完整的例子就是:

guesses = 0
number = 10

while True:
    try:
        guess =int(input("Guess my number between 1 and 100(inclusive):"))
    except:
        print("Enter a number!")
        continue

    guesses = guesses + 1  

    if guess == number:
     print("Well done! My number is:", number,"You had",guesses,"guesses")
     break
    elif guess < number :
       print ('sorry, my number is higher')
    elif guess > number:
        print ('Sorry, My number is lower')

答案 2 :(得分:0)

我喜欢@ Nsh的答案 - 它更常见,在实践中可能更好。但是如果你不喜欢使用try-catch语句和sql的粉丝...

import random

my_number = random.randint(1,100)
your_number = None
counter = 0
While your_number != my_number:
    s = input("Guess my number between 1 and 100(inclusive):")
    counter += 1
    if all(i in '0123456789' for i in s):
        your_number = int(s)
        if my_number == your_number: print 'Well done!'
        else: print 'sorry, my number is {}'.format('higher' if my_number > your_number else 'lower')

享受。