Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
abrar hamzah
199 PointsCoin flip
So i want to make a coin flip program that if a user input number of flips, it will print the answer as many times the input is. import random
coin =random.randint(1, 2)
count=int(input("number of flips: "))
for goes in range(count): if coin == 1: print("The coin came up Heads")
else: print("The coin came up Tails")
the problem is, if the input is 6, the result is 6 of either heads or tails. How to make 6 of random results?
2 Answers
Alexander Davison
65,469 PointsYou need to make a new random number for each flip, not set the random number in the beginning and use that same number for every flip.
Your fixed program might look like this:
import random
count = int(input("Enter the number of flips: "))
for goes in range(count):
coin = random.randint(1, 2)
if coin == 1:
print("The coin came up as heads")
else:
print("The coin came up as tails")
Also, your program will cause a ValueError if the user enters something like "a". Python causes an error because "a" isn't a valid number, and can't be converted to a number. So, to mkae sure the user's input is safe, you can do something like this:
import random
while True:
try:
count = int(input("Enter the number of flips: "))
except ValueError:
print("That's not a valid number!")
else:
break
for goes in range(count):
coin = random.randint(1, 2)
if coin == 1:
print("The coin came up as heads")
else:
print("The coin came up as tails")
This program will ask for input until the input is a valid number.
I hope this helps
Happy C0D1NG!
~Alex
Chris Sehnert
30,857 PointsHello Abrar...
when you call... coin =random.randint(1, 2) that represents a coin flip..... at this point your code only performs 1 flip.....and then asks "count" times..... "What was the result?"