Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python While循环/加倍或退出_Python_While Loop - Fatal编程技术网

Python While循环/加倍或退出

Python While循环/加倍或退出,python,while-loop,Python,While Loop,我知道如何使用while循环,但我不确定我需要在哪个部分发出命令以使以前的分数翻倍 是加倍还是退出 这是我目前的代码: 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:

我知道如何使用
while
循环,但我不确定我需要在哪个部分发出命令以使以前的分数翻倍

是加倍还是退出

这是我目前的代码:

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]: ")

您当前正在反复重复相同的固定输出计算:

newnumber = Original*2
Original
是一个常量,因为您只在开始时定义它,从不更改它

您应该以迭代方式使用上次运行的结果:

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]: ")

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

问自己以下问题:第二次循环
while
时,
Original
newnumber
的值是多少,您希望它们是什么?如果球员运气不好,但选择再次比赛,会发生什么?最后,你觉得幸运吗?你…吗?