python中

时间:2016-11-08 11:43:35

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

我正在编写一个程序来生成随机数,然后要求您猜测已生成的数字。 但是,作为扩展任务,我被要求使程序工作,即使输入了一个字母,所以我创建了一个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: ')

我希望这可以代替下面的粗体代码但是我需要知道要放什么而不是数字以允许猜测成为一个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.')

提前致谢

2 个答案:

答案 0 :(得分:2)

如果您查看文档。 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。 这更像是pythonic,并且当涉及子类化时会阻止你遇到奇怪的错误。

答案 1 :(得分:0)

您也可以这样使用:

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