IMAGO IMAGO - 2 months ago 10
Python Question

How can I make a while loop only run a limited number of times?

In the code below, I'd like to run the function

roll()
, after:
deal = input("Your Turn: ")
, but only up to a limited number of cycles (52)

How can I achieve that?

import random

ydeal = random.randint(1,15)
adeal = random.randint(1,15)

yscore = 0
ascore = 0

def roll():
if deal == "Deal":
print(ydeal, adeal)
if ydeal > adeal:
yscore + 1
elif ydeal < adeal:
ascore + 1
print(yscore, ascore)

deal = input("Your Turn: ")
roll()


As a side note: I noticed that when printing
yscore
and
ascore
the value does not change during the loop, how can I fix that?

Answer

Not sure about your code, but you can limit the number of loops by adding one to n on each loop, and use while n <= 52 (or any other value):

n = 1
while n <= 3:
    word = "monkey" if n == 1 else "monkeys"
    print(n, word)
    if input("press Return to increase the number of monkeys ") == "":
        n += 1

Then:

1 monkey
press Return to increase the number of monkeys 
2 monkeys
press Return to increase the number of monkeys 
3 monkeys
press Return to increase the number of monkeys 
>>>

In your situation:

n = 1
while n <= 52:
    deal = input("Your Turn: ")
    roll()
    n += 1

However, your function roll() isn't quite working as it should:

  • your ydeal and adeal are fixed values, and won't change during the game.
  • whatever you do with your variables inside the function has no effect outside, unless you set the variable to be global, or you make the function return something.

An example:

test = 5

def add_one(var):
    return var + 1

test = add_one(test)
print(test)
> 6

but that is another question :).