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!
flips = flips + 1is done only when the conditionif random.randint(0, 1) == 1is True.flips = flips + 1is now outside of theifcondition. In other languages, you often see brackets used to signify what the if condition will do if true/false