Last active
December 22, 2024 23:26
-
-
Save StrangeRanger/4e0523b964dbe22990282b413fcd7f6a to your computer and use it in GitHub Desktop.
heads_or_tails.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# Digitally flip a coin x number of times and prints the number of times the outcome was | |
# heads and tails. | |
# | |
# Version: v1.0.3 | |
# License: MIT License | |
# Copyright (c) 2020-2021 Hunter T. (StrangeRanger) | |
# | |
######################################################################################## | |
import random | |
def coin_toss(x): | |
"""Simulates flipping a coin a specified number of times. | |
Args: | |
x (int): The number of times the coin should be flipped. | |
""" | |
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)) | |
## 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) |
Author
StrangeRanger
commented
Jun 7, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment