[英]While loop/ Double or quit
I know how to use a while
loop, but I'm not sure about the part where I need to make a command to double the previous score.我知道如何使用
while
循环,但我不确定需要发出命令以将前一个分数加倍的部分。
The task is to double or quit.任务是加倍或退出。
And this is my current code :这是我当前的代码:
import random
play = 'y'
Original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
newnumber = Original*2
print (newnumber)
play = input("Play again?[y/n]: ")
You are currently repeating the same fixed output calculation over and over again:您目前正在一遍又一遍地重复相同的固定输出计算:
newnumber = Original*2
Original
is a constant since you only define it at the beginning and never change it. Original
是一个常量,因为您只在开始时定义它并且永远不会更改它。
You should instead use the result from the last run iteratively:您应该迭代地使用上次运行的结果:
import random
play = 'y'
result = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
break
else:
result *= 2
print(result)
play = input("Play again?[y/n]: ")
A for
-loop is better suited for your problem: for
循环更适合您的问题:
from itertools import count
import random
for pot in count():
if random.randint(0, 3) == 0:
print("Unlucky.... better luck next time")
break
print(2 ** pot)
if input("Play again?[y/n]: ").lower() != 'y':
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.