Skip to content

Adding Conditionals #3

@github-learning-lab

Description

@github-learning-lab

Let's add some flavor to our responses, dependent on how we roll. We can do this by using conditionals. We'll put a command that only triggers if a certain condition is met. For example, let's add "Critical Fail" in the printed statement if the die roll is a one.

In Python, we can set this as the criteria by replacing our print statement in the loop with:

if roll == 1:
  print(f'You rolled a {roll}! Critical Fail')

But what if it's not a one? We need a catch-all for all the other conditions it could be. This is done in Python with the else command. Below our if statement and the related print function, add an else statement:

else:
  print(f'You rolled a {roll}')

Now we have two different statements that can be printed. Try running your code until you have a roll that is a one and a roll that is something else.

If we have additional conditions we want to add, we can use a third type of conditional in Python: elif. This is used for a specific condition after if has been used. Try adding this elif statement between the if and else statements:

elif roll == 6:
  print(f'You rolled a {roll}! Critical Success!')

With the conditionals added, your main function should look something like this:

dice_rolls = 2
dice_sum = 0
for i in range(0,dice_rolls):
  roll = random.randint(1,6)
  dice_sum += roll
  if roll == 1:
    print(f'You rolled a {roll}! Critical Fail')
  elif roll == 6:
    print(f'You rolled a {roll}! Critical Success!')
  else:
    print(f'You rolled a {roll}')
print(f'You have rolled a total of {dice_sum}')

Leave a comment with the number of rolls it took to get a Critical Success.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions