请问我写的这个小游戏错误出在哪儿了呢?
"""用python设计第一个游戏"""temp = input("不妨猜一下小甲鱼现在心里想的是哪个数字:")
guess = int(temp)
if guess == 8:
print("还真让你给猜对了。好啦,不玩啦^_^")
else:
counts = 2
while counts > 0:
print("还剩",counts,"次机会。")
if guess > 8:
temp = input("大了,再猜:")
guess = int(temp)
if guess < 8:
temp = input("小了,再猜:")
guess = int(temp)
counts = counts - 1
if guess == 8:
print("还真让你给猜对了。好啦,不玩啦^_^")
else:
print("笨死你算了!好了,不玩啦^_^")
------------------------------------------
如果一直输入比8大的数,或者一直输入比8小的数,程序运行是正常的。如果时大时小,就会多运算一次。我大概知道原因出在哪里,但我不知道该怎么修改。请哪位大神帮忙看一下,指点一二。多谢~~
学了break就在if判断里面加一个break,没学的话就在print后面加一句counts=0
因为你 while 循环中没有设置guess == 8 时候的情况,所以一定要你输入到不符合 while 条件才会退出循环
在你代码上进行更改,参考代码:
"""用python设计第一个游戏"""
temp = input("不妨猜一下小甲鱼现在心里想的是哪个数字:")
guess = int(temp)
if guess == 8:
print("还真让你给猜对了。好啦,不玩啦^_^")
else:
counts = 2
while counts > 0:
print("还剩", counts, "次机会。")
if guess > 8:
temp = input("大了,再猜:")
guess = int(temp)
if guess < 8:
temp = input("小了,再猜:")
guess = int(temp)
counts = counts - 1
if guess == 8:
print("还真让你给猜对了。好啦,不玩啦^_^")
counts = 0
if guess != 8:
print("笨死你算了!好了,不玩啦^_^")
Twilight6 发表于 2020-11-26 13:54
因为你 while 循环中没有设置guess == 8 时候的情况,所以一定要你输入到不符合 while 条件才会退出循 ...
优化了部分代码,可以参考下:
print("不妨猜一下小甲鱼现在心里想的是哪个数字:" ,end='')
counts = 3
while counts > 0:
guess = int(input())
if guess == 8:
print("还真让你给猜对了。好啦,不玩啦^_^")
counts = 0
else:
counts = counts - 1
if guess != 8 and counts == 0:
print("笨死你算了!好了,不玩啦^_^")
exit() # exit() 函数退出程序的作用
print("还剩", counts, "次机会。")
if guess > 8:
print("大了,再猜:",end='')
if guess < 8:
print("小了,再猜:", end='')
页:
[1]