【发布时间】: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 2.x 还是 Python 3 ?
-
看看
isinstance内置函数,如isinstance(guess, int)。
标签: python-3.x error-handling syntax-error