I'm new to python and coding in general. I have an assignment for class to write a program that uses a loop to flip multiple coins multiple times. The code must:
- ask for the number of coins and how many times to flip those coins.
- Must ask again if the input is less then 0.
- Print the result of flipping each coin the specified number of times and must be random.
- Then print the total number of heads and tails. I do have to use random so suggestions of other modules or better ways to achieve randomization aren't something I'm looking for, thank you.
The output should look something like:
How many coins do you want to flip? 2
How many times do you want to flip each coin? 2
Coin 1
Flip: 1; Result: Heads
Flip: 2; Result: Tails
Coin 2
Flip: 1; Result: Tails
Flip: 2; Result: Heads
There were 2 Tails in total
There were 2 Heads in total
Here's what I tried: (I'm having to use my phone due to some irl problems to ask this so if the format is off I'm sorry!)
import random
heads = 0
tails = 0
coins = int(input("How many coins: "))
while coins !="":
if coins \<= 0:
print ("Invalid input")
coins = int(input("How many coins: "))
else:
flips = int(input("How many times to flip: "))
if flips \<= 0:
print ("Invalid input")
flips = int(input("How many times to flip: "))
else:
for n in range (0, coins):
for i in range (0, flips):
print (" ")
print ("Coin %0d" %n)
print (" ")
n = coins + 1
for flips in range (0, flips):
flip = random.randint(0,1)
if flip == 0:
heads += 1
print ("Flips: %0d;" %i, "Result: heads")
else:
tails += 1
print ("Flip: %0d;" %i, "Result: tails")
i = flips + 1
print ("total heads:", heads)
print ("total tails:", tails)
break
What I get varies wildly by the numbers I input. I might flip 4 coins 3 times and it flips 6 coins. Or 1 coin 3 times and it flips 6 coins. But 1 coin 2 times flips 1 coin 2 times. The numbers counting the coins and flips also don't work right. I get results like:
Coin 0
Flip: 0; Result: Tails
Flip: 3; Result: Heads
Coin 2
Flip: 1; Result: Tails
Flip: 3; Result: Tails.
I'm stumped and at this point all the code looks like abc soup. Any help is appreciated.
Aucun commentaire:
Enregistrer un commentaire