Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Ali AlRabeah
Ali AlRabeah
909 Points

Dice rolling game. What's wrong with my code?

When prompt it accepts any answer as "yes".

import random

def roll_dice(answer):
    print("You will get a number between 1 and 6.")
    for numbers in range(1):
        print(random.randint(1, 6))


a = True

while a == True:
    yes_or_no = input("Would you like to roll dice? Y/N ")
    if yes_or_no == "Yes" or "Yes".lower():
        roll_dice(yes_or_no)
    else:
        are_you_sure = input("Are you sure you want to exit? Y/N  ")
        if are_you_sure == "Yes" or "Yes".lower():
            print("Goodbye!")
            break
        else:
            continue

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Ali,

You are making a subtle mistake in your comparison:

if yes_or_no == "Yes" or "Yes".lower():

For the rest of the example, let's assume that the user entered no The way that or works is that it checks two boolean values (one to the left of the or, one to the right). In this case the boolean value to the left of the or is yes_or_no == "Yes". "no" is not equal to "Yes" so the left side evaluates to False.

The boolean value to the right of the or is "Yes".lower(). In Python, non-empty strings are 'truthy' so this evaluates to True.

Since the or evaluates to True if either side is True, and the right side will always be True, your if will always be triggered.

One way that you could have rewritten your comparison is to compare "Yes".lower() to yes_or_no, just like you did on the left side of the or. Alternatively, you could just make whatever value is in yes_or_no all lowercase and then you only need to make one comparison (the lowercase version of the value in yes_or_no to "yes").

Hope that clears everything up

Cheers

Alex

Ali AlRabeah
Ali AlRabeah
909 Points

Oh man what a silly mistake! Appreciate the clarification.