求助:猜数字小游戏增加报错功能
本帖最后由 EggZZ 于 2020-4-29 11:56 编辑刚刚开始学python,纠结while和if循环纠结了好久也没想出来,请大佬们帮忙修改一下, 感谢!问题1:应该在哪里添加 isinstance()
我尝试过在while循环下加,但是因为guess变量已经设定为int()了,程序直接就报错了
问题2:我自己增加了一个条件:如果猜的数字大于10,则显示数字过大,但是显得整个代码很乱,又不知道该从哪里开始简化,求解答!
感谢大佬们赐教{:10_254:}
第一次发帖,不知道缩进改的对不对,所以也贴了张代码的截屏
from random import randint
num = randint(1, 10)
guess = int(input("Enter a number:\n"))
guess_count = 0
guess_limit = 5
out_of_guess = False
while guess != num and not out_of_guess:
guess_count += 1
if guess_count < guess_limit:
if num < guess <= 10:
guess = int(input("Too Big!\n"))
elif guess < num <= 10:
guess = int(input("Too Small!\n"))
else:
guess = int(input("Number should not bigger than 10!\n"))
else:
out_of_guess = True
if out_of_guess:
print("Out of Guesses!")
break
else:
print("Bingo!")
没必要用isinstance,直接isdiigit就好了.
from random import randint
num = randint(1, 10)
guess = input("Enter a number:\n")
while not guess.isdigit():
guess = input("Enter a number:\n")
guess = int(guess)
guess_count = 0
guess_limit = 5
out_of_guess = False
while guess != num:
guess_count += 1
if guess_count < guess_limit:
if num < guess <= 10:
guess = int(input("Too Big!\n"))
elif guess < num <= 10:
guess = int(input("Too Small!\n"))
else:
guess = int(input("Number should not bigger than 10!\n"))
else:
print("Out of Guesses!")
break
else:
print("Bingo!") qiuyouzhi 发表于 2020-4-29 12:02
没必要用isinstance,直接isdiigit就好了.
感谢感谢, 然后 out_of_guess 这个条件其实是没必要的是吗? EggZZ 发表于 2020-4-29 12:22
感谢感谢, 然后 out_of_guess 这个条件其实是没必要的是吗?
没必要,而且还要加一个判断,看着更麻烦。 qiuyouzhi 发表于 2020-4-29 12:24
没必要,而且还要加一个判断,看着更麻烦。
{:10_281:}{:10_281:}{:10_281:}
页:
[1]