Dice roll generator using Python + error handling

Today, we are going to build a dice roll generator using Python. The code allows the user to input the number of dice they want to roll and then outputs the result of the roll. The code makes use of the ‘random’ library in Python to generate a random number between 1 and 6, which represents the outcome of rolling a single dice. The code also includes error handling, so if the user inputs an invalid number of dice, it will prompt them to enter a valid number. This code is a great starting point for those who are new to programming and want to learn more about basic coding concepts such as user input, error handling, and generating random numbers.

The video

Error handling in python

The “try-except” statement in Python is used to handle exceptions, or run-time errors, that occur during the execution of a program. It allows the programmer to write code that can gracefully handle unexpected conditions, such as missing files, invalid inputs, or network errors, without crashing the program.

The basic structure of the “try-except” statement consists of a “try” block, which contains the code that might raise an exception, followed by one or more “except” blocks, each of which contains the code to handle a specific type of exception. If an exception occurs in the “try” block, the interpreter immediately transfers control to the first matching “except” block, skipping over any remaining statements in the “try” block.

In addition to handling specific exceptions, the “except” block can also include a general “except” clause that catches all exceptions not handled by the preceding “except” blocks. This is useful for logging or reporting the error, or for displaying an error message to the user. It is important to note that the general “except” clause should be placed last, so that it only catches exceptions that were not handled by the more specific “except” blocks.

Here’s a simple example that demonstrates how to use the “try-except” statement in Python:

try:
    # code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # code to handle the exception
    print("Cannot divide by zero!")
else:
    # code to run if there was no exception
    print("The result is:", result)

In this example, the “try” block contains the code that performs a division operation. If the divisor is 0, a ZeroDivisionError will be raised. The “except” block contains the code to handle this exception, which simply prints an error message to the screen. The “else” block contains code that will only run if the “try” block completes without raising any exceptions. In this case, it prints the result of the division operation.

Dice roll generator using Python

This code is a simple dice-rolling game. It asks the user for the number of dice they would like to roll and then generates random values for that number of dice. If the user inputs a value that is not 1 or 2, a ValueError will be raised and an error message will be displayed, asking the user to enter 1 or 2. If the input is valid, the program will generate random values for the corresponding number of dice. The game will continue to run until the user decides to stop by entering something other than yes or y.

import random
import os


def num_dice():
    while True:
        try:
            num_dice = input('Number of dice: ')
            valid_responses = ['1', 'one', 'two', '2']
            if num_dice not in valid_responses:
                raise ValueError('1 or 2 only')
            else:
                return num_dice
        except ValueError as err:
            print(err)


def roll_dice():
    min_val = 1
    max_val = 6
    roll_again = 'y'

    while roll_again.lower() == 'yes' or roll_again.lower() == 'y':
        os.system('cls' if os.name == 'nt' else 'clear')
        amount = num_dice()

        if amount == '2' or amount == 'two':
            print('Rolling the dice...')
            dice_1 = random.randint(min_val, max_val)
            dice_2 = random.randint(min_val, max_val)

            print('The values are:')
            print('Dice One: ', dice_1)
            print('Dice Two: ', dice_2)

            roll_again = input('Roll Again[y or yes]? ')

        else:
            print('Rolling the die...')
            dice_1 = random.randint(min_val, max_val)
            print(f'The value is: {dice_1}')

            roll_again = input('Roll Again[y or yes]? ')


if __name__ == '__main__':
    roll_dice()

The code contains two functions: num_dice and roll_dice.

The num_dice function is used to obtain the number of dice the user wants to roll. It uses a while loop to keep prompting the user for input until a valid response is received. If the user inputs a value that is not 1 or 2, a ValueError is raised and an error message is displayed. If the input is valid, the function returns the number of dice to roll.

The roll_dice function is used to simulate the rolling of dice. It uses a while loop that continues to execute as long as the user wants to roll the dice (as indicated by the input roll_again). The function first calls the num_dice function to determine the number of dice to roll. If the user wants to roll two dice, the function generates two random values between 1 and 6 and displays them. If the user wants to roll only one die, the function generates one random value and displays it. After each roll, the function prompts the user if they would like to roll again.

Was this helpful?
[3]