马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在论坛上看完第五讲之后,小甲鱼讲到游戏改进的地方:用户输入错误类型时,题型用户重新输入,并提供了以下代码:
temp = input("不妨猜一下小甲鱼现在心里想的是哪个数字:")
# 这种想法是因为 type(1) 会返回 <class 'int'>,如果 type(temp) 返回结果一致说明输入是整数。
while type(temp) != type(1):
print("抱歉,输入不合法,", end='')
temp = input("请输入一个整数:")
我想把这段程序插入到以前写的程序中,结果出现了问题。以前的代码如下:
import random
secret = random.randint(1,10)
temp = input('guess which number I am thinking of : ')
guess = int(temp)
times = 1
while(guess != secret) and (times < 3):
if guess > secret:
print('oh,it\'s too big')
else:
print('oh, it\'s too small')
temp = input('try again: ')
guess = int(temp)
times = times +1
if (times <= 3) and (guess == secret):
print('Are you a genius ? ')
print('hng, there is no award even so')
else:
print('Well, game ove given you three times')
插入之后,我把上面的代码修改如下:
import random
secret = random.randint(1,10)
temp = input('guess which number I am thinking of : ')
guess = int(temp)
times = 1
if isinstance(temp,int):
while(guess != secret) and (times < 3):
if guess > secret:
print('oh,it\'s too big')
else:
print('oh, it\'s too small')
temp = input('try again: ')
guess = int(temp)
times = times +1
if (times <= 3) and (guess == secret):
print('Are you a genius ? ')
print('hng, there is no award even so')
else:
print('Well, game ove given you three times')
else:
print('抱歉,输入不合法,', end = ' ')
temp = input('注意,请输入一个整数:')
但是这样修改是不对的,正如小甲鱼所说, input() 的返回值始终是字符串,所以 type(temp) 永远是 <class 'str'>
我的问题是,怎样修改才能实现原来的功能?
>>> n = "123"
>>> n.isdigit()
True
>>> m = "abc"
>>> m.isdigit()
False
>>>
|