Skip to content

Instantly share code, notes, and snippets.

@StrangeRanger
Last active March 7, 2022 19:51
Show Gist options
  • Save StrangeRanger/4e0523b964dbe22990282b413fcd7f6a to your computer and use it in GitHub Desktop.
Save StrangeRanger/4e0523b964dbe22990282b413fcd7f6a to your computer and use it in GitHub Desktop.
heads_or_tails.py
#!/usr/bin/env python3
#
# Version: v1.0.3
# License: MIT License
# Copyright (c) 2020-2021 Hunter T. (StrangeRanger)
#
########################################################################################
"""
Digitally flip a coin x number of times and prints the number of times the outcome was
heads and tails.
"""
####[ Imports ]#########################################################################
import random
####[ Functions ]#######################################################################
def coin_toss(x):
"""Flip a coin x number of times.
Parameters
----------
x : int
User provided integer.
"""
heads = 0
tails = 0
for i in range(x):
toss = random.randint(0, 1)
if toss == 0:
heads += 1
else:
tails += 1
print("Total tosses: {}\nHeads: {}\nTails: {}".format(x, heads, tails))
####[ Main ]############################################################################
## Make sure that the user input is valid.
while True:
try:
toss_number = int(input("How many times do you want to toss the coin?\n"))
# ValueError is produced when 'toss_number' is not an integer.
except ValueError:
print("Invalid input: only numbers are accepted as input\n")
continue
## Prevent 'toss_number' from being a negative number.
if toss_number < 0:
print("Invalid input: only positive numbers are accepted as input\n")
continue
break
coin_toss(toss_number)
@StrangeRanger
Copy link
Author

Project Tracker

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment