-1

So brand new to python, and I've come across something I can't explain, much less put in to words to find a possible answer for. I've made a little coin flipping program:

import random

print("I will flip a coin 1000 times")
input()

flips = 0
heads = 0

while flips < 1000:
    if random.randint(0, 1) == 1:
        heads = heads + 1
        flips = flips + 1

print()
print("Out of 1000 coin tosses, heads came up " + str(heads) + " times!")

This version of the program does not work, it tells me after 1000 flips, there have been 1000 heads every time.

import random

print("I will flip a coin 1000 times")
input()

flips = 0
heads = 0

while flips < 1000:
    if random.randint(0, 1) == 1:
        heads = heads + 1
    flips = flips + 1

print()
print("Out of 1000 coin tosses, heads came up " + str(heads) + " times!")

This version of the program works perfectly however, notice I have changed the indentation of "flips" in the while loop. Can anyone tell me why this is? Thanks in advance!

2
  • 1
    In the first case flips = flips + 1 is done only when the condition if random.randint(0, 1) == 1 is True. Commented Nov 22, 2016 at 12:55
  • The indentation means that flips = flips + 1 is now outside of the if condition. In other languages, you often see brackets used to signify what the if condition will do if true/false Commented Nov 22, 2016 at 14:32

2 Answers 2

1

Python language is indentation dependent. Unlike most C-based languages, it uses indentation to delimit blocks.

So your two scripts have a different semantic:

if random.randint(0, 1) == 1:
    heads = heads + 1
    flips = flips + 1

...will increment both variables if the condition is True.

if random.randint(0, 1) == 1:
    heads = heads + 1
flips = flips + 1

...will increment heads only if the condition is True, and will always increment flips

Sign up to request clarification or add additional context in comments.

Comments

1

That's because if that "flips" line is in the if, then it will only execute if it is heads. Therefore, your coin flip count only increments when it's a head, and so by the time flips reached 1000, it means you've executed the if 1000 times and got 1000 heads.

(When you get a tail, flips won't increment and the loop keeps going and nothing happens)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.