【问题标题】:type identification and conversion for error traping in pythonpython中错误捕获的类型识别和转换
【发布时间】:2016-11-08 11:43:34
【问题描述】:

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

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

这是我的伪代码:

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

我想用它来代替下面的粗体代码,但是我需要知道放什么而不是数字,以便让猜测变成一个 int,这样我就可以逃脱 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.')

提前致谢

【问题讨论】:

标签: python-3.x error-handling syntax-error


【解决方案1】:

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

这里列出了一些方法,例如 str.isnumeric,它们可以帮助您确定字符串中的内容。

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

另外值得一提的是,在 python 中进行类型检查时,您应该使用 isinstance https://docs.python.org/2/library/functions.html#isinstance。 这更符合 Python 风格,并且可以防止您在子类化时遇到奇怪的错误。

【讨论】:

    【解决方案2】:

    你也可以这样用:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 2016-11-10
      相关资源
      最近更新 更多