我是一个长期潜伏的第一次发问者。我试着自学Python,当我研究我的问题时,我找不到答案。如果删除第一个While循环,下面的代码就会运行,但目前它似乎没有进入第二个while循环。我想我可能是在引导我在工作中使用的内部VBA,这是我第二次尝试Python。我已经尝试了改变第一个,所以它不仅仅是真实的,在第二个时候尝试了变体。这里的意图是研究一个骰子池技工为我想和模型滚动多D6s,5-6爆炸,3+成功和1-2失败。最终,我希望它运行,滚动骰子,返回骰子列表,成功的数目等,然后重置,要求用户的骰子数目再次滚动。
import random
Scount = 0
Xcount = 0
Fcount = 0
rollcount = 0
cheat = 0
NoOfDice = 1
Dicelist = []
while True:
print ("Input number of dice to roll")
NoOfDice=input()
while cheat<int(NoOfDice):
rand = random.randint(1, 6)
Dicelist.append(rand)
if rand <= 4:
cheat += 1
if rand >= 3:
Scount += 1
if rand >= 2:
Fcount += 1
if rand <= 5:
Xcount += 1
print (Dicelist)
print ("We rolled " + str(NoOfDice) + " you got " + str(Scount) + " number of succeses with " + str(Xcount) + " number of dice exploded with " + str(Fcount) + " dice failed")谢谢大家,感谢你们的时间!
发布于 2018-03-06 22:20:21
第一个while循环的条件基本上是True,这意味着它是一个无限循环。
您的第二个循环看起来不像是在运行,但肯定是运行的(只要输入大于0的数字)。
您的程序没有输出的原因是您的print()语句在无限循环之后,所以它们永远不会运行。这就是当您删除无限循环时,程序按需要运行的原因。
要解决这个问题,只需将print()语句移到第一个循环中,但在最后。
注意:如果您希望在运行程序时有时间阅读正在打印的内容,则应该将print()s更改为input()s,因为这意味着第一个循环只在您按下Enter之后循环。
附加注意:random.randint(1, 6)返回的值从0到5而不是从1到6。查看if语句中的值,您可能希望将代码更改为:
rand = random.randint(1,6) + 1发布于 2018-03-06 23:30:04
您的代码可以使用2个if语句而不是4个语句进一步压缩。下面是我建议的解决方案。我把它包装成一个函数,但你不必这么做。我将把它留给您思考,并决定如何在第二个while循环完成执行后,转义第一个"while“循环。
def rolldice ():
... while True:
... scount = 0
... xcount = 0
... fcount = 0
... cheat = 0
... NoOfDice = ''
... DiceList = []
... NoOfDice = input ('Number of dice to roll: ')
... while cheat < int (NoOfDice):
... rand = random.randint(1, 6)
... DiceList.append (rand)
... if rand <= 5:
... cheat += 1
... xcount += 1
... if rand >= 2:
... fcount += 1
... scount += 1
... print ('Dice List: ', DiceList)
... print ('Number of dice rolled:', NoOfDice)
... print ('Success Count: %d' % scount)
... print ('Exploded Count: %d' % xcount)
... print ('Failed Count: %d' % fcount)
...
>>> rolldice()
Number of dice to roll: >? 3
Dice List: [2, 3, 1]
Number of dice rolled: 3
Success Count: 2
Exploded Count: 3
Failed Count: 2
Number of dice to roll: >? 1
Dice List: [5]
Number of dice rolled: 1
Success Count: 1
Exploded Count: 1
Failed Count: 1
Number of dice to roll:https://stackoverflow.com/questions/49140860
复制相似问题