How can I make a while loop only run a limited number of times?
<p>In the code below, I'd like to run the function <code>roll()</code>, after: <code>deal = input("Your Turn: ")</code>, but only up to a limited number of cycles (52)</p>

<p>How can I achieve that?</p>

<pre><code>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 &gt; adeal:
            yscore + 1
        elif ydeal &lt; adeal:
            ascore + 1
        print(yscore, ascore)

deal = input("Your Turn: ")
roll()
</code></pre>

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

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

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

print("\nOoops, we ran out of monkeys...")
</code></pre>

<p>Then:</p>

<pre><code>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 

Ooops, we ran out of monkeys...
</code></pre>

<p>In your situation:</p>

<pre><code>n = 1
while n &lt;= 52:
    deal = input("Your Turn: ")
    roll()
    n += 1
</code></pre>

<p>However, your function <code>roll()</code> isn't quite working as it should:</p>

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

<p>An example:</p>

<pre><code>test = 5

def add_one(var):
    return var + 1

test = add_one(test)
print(test)
&gt; 6
</code></pre>

<p>but that is another question :).</p>

python