python 中用于错误捕获的类型识别和转换

type identification and conversion for error traping in python

我正在编写一个程序来生成随机数,然后要求您猜测已生成的数字。 然而,作为一项扩展任务,我被要求让程序运行,即使输入的是一个字母,所以我创建了一个 while 循环来检查变量 guess 中的日期类型。但我不知道如何让它识别 python.

中字母和数字之间的区别

我需要找到一种方法来检查一个字符串,看它是否只包含数字,如果是,我需要将变量转换为 int,以便程序可以继续,但是如果它不只包含数字我需要它来要求用户再次输入数字

这是我的伪代码:

while type(guess) != type(int)
    if type(guess) == type (**number**):
        guess = int(guess)
    else:
        guess = input('You did not input a number try again: ')

我想用它来代替下面的粗体代码,但是我需要知道用什么代替数字来让猜测变成一个整数,这样我就可以逃脱 while 循环。

这是我的原始代码:(我要替换的代码是 * *

突出显示的第一个 while 循环
import random
x=random.randint(1,100)
print (x)
guess = (input('Can you guess what it is? '))
num_guess=1
***while type(guess) != type(int):
    if type(guess) == type(int):
        guess = int(guess)
    else:
        guess = input('You did not input a number try again: '***)    
while guess != x:
    if guess < x:
        print ('No, the number I am thinking of is higher than ' + str(guess))
        guess = int(input('Guess again: '))
    elif guess > x:
        print ('No, the number I am thinking of is lower than ' + str(guess))
        guess = int(input('Guess again: '))
    else:
        guess = int(input('Guess again: '))
    num_guess = num_guess +1

print ('Well done! The answer was ' + str(x) + ' and you found it in ' + str(num_guess) + ' guesses.')

提前致谢

如果您查看文档。 https://docs.python.org/3/library/stdtypes.html#str.isnumeric

此处列出了一些方法,例如 str.isnumeric,可帮助您确定字符串中的内容。

至于你的代码,如果你使用 python 2 你应该使用 raw_input 而不是输入。这将为您提供所有输入作为字符串供您使用。如果你想确认答案,你必须将它们转换成一个数字。

另外值得一提的是,在 python 中进行类型检查时,您应该使用 isinstance https://docs.python.org/2/library/functions.html#isinstance。 这更 pythonic 并且在子类化时阻止你 运行 陷入奇怪的错误。

你也可以这样使用:

import random
x = random.randint(1,100)
#Current guess count
num_guess=1
#maximum guess count
max_guess_guess = 3
while 1:
    try:
        guess = int(raw_input(' Can you guess what it is? '))
        if guess == x:
            print ('Well done! The answer was ' + str(x) + ' and you found it in ' + str(num_guess) + ' guesses.')
            break  
        elif guess < x:
            print ('No, the number I am thinking of is higher than ' + str(guess))
        elif guess > x:
            print ('No, the number I am thinking of is lower than ' + str(guess))
    except Exception, e:
        pass  
    if num_guess >= max_guess_guess:
        print ('You are fail to guess! The guess guess was over please try next time.' )
        break
    num_guess+=1