简体   繁体   中英

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.

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM