这是我的代码,但正如标题所说,我不能打破,如果我把东西放在一边真实,生活低于0,没有任何反应。
from random import randint
import sys
value = int(randint(1,10))
lives = int(5)
userinp = int(0)
if lives == 0:
print("no lives :(")
while True:
if lives != 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
if lives == 0:
print("this")
答案 0 :(得分:2)
你的循环基本上是这样的:
while True:
if lives != 0:
# do stuff with lives
这是一个无限循环。即使lives == 0
,循环也不会中断,因为这个条件作为循环块的一部分进行测试,而不是循环条件。
你应该这样做:
while lives != 0:
# do stuff with lives
甚至while lives > 0:
如果你在1次循环迭代中设法放弃了几个生命(这里似乎不可能,但比对不起更安全)。
既然你似乎想要学习Python,那么你可能还需要学习和改进其他一些东西:
无需在此处将整数转换为整数:
value = int(randint(1,10))
lives = int(5)
userinp = int(0)
5
和0
以及randint(1,10)
等数字本身就是整数。 "5"
和"0"
是包含数字作为单个字符的字符串,需要在与整数进行比较之前进行转换,但此处不需要。 randint()返回整数。
这是死代码,因为您已将lives
设置为5
上述2行,之后未对其进行修改:
if lives == 0:
print("no lives :(")
您应该检查用户是否实际输入了有效的整数可转换值而不是任意字符串:(continue
将跳到下一个循环迭代,因此它将再次询问用户输入而不递减{{1 }}
lives
无需一次又一次地将已经整数userinp = input("Please enter a number from 1 to 10: ")
if not userinp.isnumeric(): continue
转换为整数,并且需要再次:
value
避免使用if int(userinp) == int(value):
elif int(userinp) > int(value):
elif int(userinp) < int(value):
,您可能只需sys.exit()
(离开循环并继续。
最后,Python有方便的break
运算符,因此您可以编写-=, +=, *=, /=
而不是lives -= 1
答案 1 :(得分:1)
while True
是一个无限循环,消耗所有CPU周期的100%并且永远不会中断 - 因为while <condition>
仅在条件变为False
时结束,但是永远不会,因为它总是True
!
尽量不要与循环的性质作斗争:
while True:
if lives != 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
if lives == 0: # indent condition to fall within the loop
print("this")
if lives < 0: # add an extra case to handle what you want
break
答案 2 :(得分:0)
您必须在while
之后通过lives == 0
或更改while条件来中断break
。
答案 3 :(得分:0)
这是我的解决方案,如果发生特定事件,您可以专门设置break
条件以结束您的while循环。
while lives > 0:
print(value)
print("You currently have: ", lives, " lives left")
userinp = input("Please enter a number from 1 to 10: ")
if int(userinp) == int(value):
print("Well done you wn :D")
sys.exit()
elif int(userinp) > int(value):
print("Your guess was too high please guess again")
lives = lives - 1
elif int(userinp) < int(value):
print("Your guess was too low please guess again")
lives = lives - 1
print("this")