Python中的无限循环错误
我这里有一个简短的代码。但它不是使用python在WingIDE4.1中打印的,因为它是一个无限循环。有什么想法我可以添加或如何修复它,使其打印Python中的无限循环错误,python,python-2.7,infinite-loop,Python,Python 2.7,Infinite Loop,我这里有一个简短的代码。但它不是使用python在WingIDE4.1中打印的,因为它是一个无限循环。有什么想法我可以添加或如何修复它,使其打印 import random coins = 1000 wager = 2000 while ((coins>0) and (wager!= 0)): x = random.randint(0,10) y = random.randint(0,10) z = random.randint(0,10) print x, print y, print
import random
coins = 1000
wager = 2000
while ((coins>0) and (wager!= 0)):
x = random.randint(0,10)
y = random.randint(0,10)
z = random.randint(0,10)
print x,
print y,
print z
您的代码从不更改
硬币
或赌注
,因此while
条件始终为真:
也许您还想从硬币
或赌注
中减去x
、y
或z
至于为什么代码不在Wing IDE中打印;这完全取决于缩进。如果
print
语句不是循环的一部分,则它们永远不会到达,也永远不会执行。尝试创建一个不无限运行的循环。因为while循环中的中断条件没有修改
在您的情况下,中断条件是当下注不是0
和硬币>0
时,因此您必须修改代码中的硬币
或下注
变量,例如
import random
coins = 1000; wager = 2000
while coins > 0 and wager is not 0:
x,y,z = [random.randint(0,10)]*3
print x,y,z
wager-= 1000
coins-= 100
由于@martijn缩进在python中很重要,请参见:
[out]:
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
当打印x
未缩进时:
for _ in range(10):
x = 'hello world'
print x
[out]:
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
在时间结束之前,你发布的代码只能选择3个伪随机数。您必须添加一些赢/输条件。到目前为止,x、y和z只是数字。如果你想进行赌博游戏,你必须添加一些获胜条件,如:
if x + y + z > 10
只是一个例子,但是你的程序需要能够判断玩家是否赢了。然后,它需要对玩家的总金额进行更改,并要求进行新的下注。您还可能需要添加逻辑,以确保玩家不能下注超过他们的赌注
import random
coins = 1000
wager = 0
while True: #main loop
print('you have {} coins'.format(coins))
if coins == 0: #stops the game if the player is out of money
print('You are out of money! Scram, deadbeat!')
break
while wager > coins or wager == 0: #loops until player enters a non-zero wager that is less then the total amount of coins
wager = int(input('Please enter your bet (enter -1 to exit): '))
if wager < 0: # exits the game if the player enters a negative
break
print('All bets are in!')
x = random.randint(0,10)
y = random.randint(0,10)
z = random.randint(0,10)
print(x,y,z) #displays all the random ints
if x + y +z > 10: #victory condition, adds coins for win
print('You win! You won {} coins.'.format(wager))
coins += wager
else: #loss and deduct coins
print('You lost! You lose {} coins'.format(wager))
coins -= wager
wager = 0 # sets wager back to 0 so our while loop for the wager validation will work
随机导入
硬币=1000
赌注=0
如果为True:#主循环
打印('您有{}枚硬币'。格式(硬币))
如果硬币=0:#如果玩家缺钱,则停止游戏
打印(“你没钱了!滚开,死鬼!”)
打破
当下注>硬币或下注==0时:#循环直到玩家输入小于硬币总数的非零下注
下注=int(输入('请输入您的下注(输入-1以退出):'))
如果下注<0:#如果玩家输入负数,则退出游戏
打破
打印('所有赌注都在!')
x=random.randint(0,10)
y=random.randint(0,10)
z=随机随机随机数(0,10)
打印(x,y,z)#显示所有随机整数
如果x+y+z>10:#胜利条件,则为胜利添加硬币
打印('您赢了!您赢了{}个硬币。'.format(下注))
硬币+=赌注
其他:#损失并扣除硬币
打印('你输了!你输了{}个硬币'。格式(下注))
硬币-=赌注
下注=0#将下注设置回0,这样我们的下注验证while循环就可以工作了
缩进在Python中很重要;请将之后的行缩进,同时将正确缩进以反映您的代码,好吗?