Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lovemycodesnippets/88fe39a6bab1de8a237690d2bdaadb2e to your computer and use it in GitHub Desktop.
Save lovemycodesnippets/88fe39a6bab1de8a237690d2bdaadb2e to your computer and use it in GitHub Desktop.
import random
def get_num_dice():
"""Asks user for number of dice, continues asking if invalid."""
while True:
try:
num_dice = int(input("How many dice would you like to roll? "))
if num_dice < 1:
print("Please enter a positive integer.")
else:
return num_dice
except ValueError as e:
print(f"Invalid input: {e}")
def get_num_sides():
"""Asks user for number of sides, continues asking if invalid."""
while True:
try:
num_sides = int(input("How many sides does each dice have? "))
if num_sides <= 0:
print("Please enter a positive integer.")
else:
return num_sides
except ValueError as e:
print(f"Invalid input: {e}")
def roll_dice(num_dice, num_sides):
"""Rolls specified number of dice with specified number of sides."""
results = [random.randint(1, num_sides) for _ in range(num_dice)]
return str(results).replace("'", ', ').strip('[]')
def main():
print("Welcome to Dice Roller!")
num_dice = get_num_dice()
if num_dice == 0:
print("Not rolling any dice.")
return
num_sides = get_num_sides()
results_str = roll_dice(num_dice, num_sides)
# Display the results
print(f"Rolling {num_dice}d{num_sides}")
if len(results_str) > 5:
half_points = (len(results_str) + 4) // 2
first_half = ', '.join([str(result)[:half_points] for result in results.split(',')[0:-1]])
second_half= [result[half_points:]for result in results.split(',')]
else:
print(f'{results_str}')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment