Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Coin flip with report problem
-
Hi,
Having trouble with code for a coin flip simulation program I’m trying to set up for a Stats class. The goal is to ask how many times to flip the coin, then show the results after the simulation. I’m pretty new to Python and programming, so I checked stack overflow and found the code below to try. Problem is, nothing is printing to the console to review. Any thoughts?import random def coinToss(): number = input("Number of times to flip coin: ") recordList = [] heads = 0 tails = 0 for amount in range(number): flip = random.randint(0,1) if (flip == 0): print("Heads") recordList.append("Heads") else: print("Tails") recordList.append("Tails") print(str(recordList)) print(str(recordList.count("Heads")) + str(recordList.count("Tails"))) ```
-
My first guess would be that since this is a function, you’ll need to call it. Add the following line to the bottom of your code:
coinToss()
On the command line, at least, that causes the code to ask for a number and then toss the coin that many times.
-
@jerry thanks!! That worked!
-
What a great sample program. I too am a beginner programmer. Your code has been fun to play with. I messed around and did some changes you might like. I made it just print out the final result, even runnng it to 100000 coin flips, it fast enough to run big numbers
import random def coinToss(): number = int(input("Number of times to flip coin: ")) recordList = [] Heads = 0 Tails = 0 for amount in range(number): flip = random.randint(0,1) if (flip == 0): #print("Heads") recordList.append('Heads') else: #print("Tails") recordList.append("Tails") #print(str(recordList)) s = (str(recordList.count("Heads")) + ' heads ' + str(recordList.count("Tails")) + ' tails') print(s) print() coinToss()
-
- use .input().strip() to gracefully deal with leading or trailing whitespace
- use random.choice() to avoid the conversion step
- simplify with list comprehension
- print with f-string on Python 3.6 and later
import random def coinToss(): number = int(input("Number of times to flip coin: ").strip()) flips = [random.choice(('Heads', 'Tails')) for _ in range(number)] print(f'{flips.count("Heads")} heads, {flips.count("Tails")} tails\n') coinToss()
-
Wow
The economy of your art is exquisite
-
@ccc
Beauty ! -
This post is deleted! -
This post is deleted!