在猜数字游戏中加入判断输入数是否为整数的问题
麻烦诸位了。我调好了这个代码后
temp = input('猜数字')
m = str(temp)
while m.isdigit() != isinstance(1,int):
print('抱歉,输入不合法')
temp = input('请输入一个整数')
m = str(temp)
else:
print('开始游戏吧')
想把它带入到写的猜数字游戏中(👇),但是输入小数后无法判断。
import random
secret = random.randint(1,10)
temp = input('猜数字,1~10\n')
guess = int(temp)
m = str(temp)
count = 1
while m.isdigit() != isinstance(1,int):
print('输入错误',end='')
temp = input('请重新输入一个整数')
m = str(temp)
else:
while guess != secret and count < 3:
if guess > secret:
print('大啦大啦',end='')
else:
print('小了小了',end='')
temp = input('再试一次吧')
guess = int(temp)
count += 1
if guess == secret and count < 3:
print('恭喜你答对啦')
else:
print('game over!')
我不太清楚具体哪里有问题,请各位大佬给萌新指导一下,感激不尽 我重新写了一下,你看看
import random
secret = random.randint(1,10)
guess = 0
times = 3
while guess != secret and times:
temp = input('请输入一个数字:')
while not temp.isdigit():
print('输入错误',end='\n')
temp = input('请重新输入一个整数:')
guess = int(temp)
times -= 1
if guess > secret:
print('大啦大啦,再试一次吧',end='\n')
elif guess < secret:
print('小了小了,再试一次吧',end='\n')
else :
print('恭喜你答对啦')
print('game over!') 首先我复制了你的代码,输入小数,报错如下:
5.5
Traceback (most recent call last):
File "C:\Users\aaaa\bbbb\Python\Code\daily script.py", line 5, in <module>
guess = int(temp)
ValueError: invalid literal for int() with base 10: '5.5'
我个人理解的原因是当temp复制为字符串'5.5'时, int(temp)无法将‘’5.5‘’转换为整型。
针对“当输入非整型内容时,让运行结果可以提示输入错误”这个目的,修改代码如下:
temp = input('猜数字,1~10:')
while 1:
if temp.isdigit() == False:
print('输入错误', end = '')
temp = input('请重新输入一个整数:')
continue
抛砖引玉,希望能帮到你。{:5_91:}
页:
[1]