Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
heads_or_tails.py
#!/usr/bin/env python3
########################################################################################
#
# Version
# -------
# v1.0.1
#
# License
# -------
# MIT License
# Copyright (c) 2020-present Hunter T.
#
########################################################################################
"""
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):
"""Perform coin tosses for 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 ]############################################################################
# Makes sure that user input is valid
while True:
try:
toss_number = int(input("How many times do you want to toss the coin?\n"))
# ValueError produced when toss_number is not an integer
except ValueError:
print("Invalid input: only numbers are accepted as input\n")
continue
# Prevents 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment