0

Every time I enter 4, 6 or 12 it doesn't accept it. Why? The code looks fine to me. Please tell me how to correct or what to change.

import random
def roll_the_dice():

    print("Roll The Dice")
    print()
    repeat = True

    while repeat:
        number_of_sides = input("Please select a dice with 4, 6 or 12 sides: ")
        if (number_of_sides in [4,6,12] and len(number_of_sides) == 0 and 
            number_of_sides == int):
            user_score = random.randint(1,number_of_sides)
            print("{0} sided dice thrown, score {1}".format(
                                     number_of_sides,user_score))
            roll_again = input("Do you want to roll the dice again? ")
            roll_again.lower()
            if roll_again == "no":
                print("Have a nice day")
                repeat = False
            elif len(roll_again) == 0:
                print("Error please type 'yes' or 'no'")
                roll_again = input("Do you want to roll the dice again? ")
        else:
            print("You have entered an incorrect value, please try again")
            number_of_sides = input("Please select a dice with 4, 6 or 12 sides: ")
1
  • I'm not sure how it accepts any value. number_of_sides cannot simultaneously be one of 4, 6, or 12 and be a string of length 0. In no case can you enter a string that is equal to the type int. Commented Jun 8, 2013 at 13:31

3 Answers 3

7

In Python 3, when using input(), it returns a string. Thus, you would have something like "4". And "4" is not 4.

So in your script, specifically at the if number_of_sides in [4,6,12], it will always be False, because you are really saying if "4" in [4,6,12] (I'm just doing 4 as an example).

Convert the string to an integer:

>>> int("4")
4

It also looks like you are trying to determine if an input was given. len(...) == 0 is not needed. You can just say if number_of_sides. Because an empty string is False, and if one was entered, then the if-statement will not execute.


Also, number_of_sides == int is not the way to check if an object is an integer. Use isinstance():

>>> isinstance("4", int)
False
>>> isinstance(4, int)
True

Some other tiny things:

  • .lower() does not sort the string in place, as strings are immutable in python. You might just want to attach .lower() onto the end of the input().

  • You might also want to use a while loop for your second input. Observe:

    roll_again = ''
    while True:
        roll_again = input('Do you want to roll the dice again? ')
        if roll_again in ('yes', 'no'):
            break
        print("You have entered an incorrect value, please try again")
    
    if roll_again == "no":
        print("Have a nice day")
        repeat = False
    else:
        print("Let's go again!")
    
Sign up to request clarification or add additional context in comments.

12 Comments

Even if it was an integer, calling len() on it doesn't work. Maybe it should be n in ['4', '6', '12'] instead?
number_of_sides == int would also always return False.
@UlrichEckhardt Or just if int(number_of_sides) in [4, 6, 12], but you are absolutely correct yes.
There is too much wrong that doesn't work. The OP should have made smaller steps and/or reduced the code to the smallest possible piece that doesn't behave as expected. Oh, and saying the exact error and expectations help, too.
how about if i do int(input("Please select a dice with 4, 6 or 12 sides: "))
|
2

Haidro gave you the reason, but here is a different way to approach your problem:

def get_dice_size():
    dice_size = input('Enter the number of sides on the dice: ')
    while dice_size not in ['4','6','12']:
       print 'Sorry, please enter one of 4, 6 or 12:'
       dice_size = input('Enter the number of sides on the dice: ')
    return int(dice_size)

def main():
   dice_size = get_dice_size()
   repeat = True

   while repeat:
       print('Rolling the dice...')
       user_score = random.randint(1,dice_size)
       print("{0} sided dice thrown, score {1}".format(dice_size,user_score))
       roll_again = input("Do you want to roll the dice again? ")
       if roll_again.lower() == 'yes':
           dice_size = get_dice_size()
       else:
           repeat = False

   print('Thank you for playing!')

3 Comments

OP is using python 3, I'm presuming by the syntax. So print() and not print :)
Well, strictly speaking print() will work in Python 2.7 as well, but you are probably right.
Also, this looks really clean. I'm upvoting this.
0

You should change your script like shown below.

This is the important part:

    try:
        number_of_sides = int(input("Please select a dice with 4, 6 or 12 sides: "))
    except ValueError:
        wrong = True

Convert to int right at input time with int(input("…. If the user enters anything that cannot be converted into an integer Python will raise a ValueError. You can catch this, show a message and go to the start of the loop with continue.

import random


def roll_the_dice():

    print("Roll The Dice")
    print()
    repeat = True

    while repeat:
        wrong = False
        try:
            number_of_sides = int(input("Please select a dice with 4, 6 or 12 sides: "))
        except ValueError:
            wrong = True
        if wrong or number_of_sides not in [4,6,12]:
            print("You have entered an incorrect value, please try again")
            continue
        else:
            user_score = random.randint(1,number_of_sides)
            print("{0} sided dice thrown, score {1}".format(
                                     number_of_sides,user_score))
            roll_again = input("Do you want to roll the dice again? ")
            if roll_again in ('y', 'Y', 'yes', 'Yes'):
                continue
            else:
                print("Have a nice day")
                repeat = False

roll_the_dice()

4 Comments

Logic here needs some work. Conder at the first while loop, someone enters "1356"; what will happen?
1356 is not in [2, 4, 6] so else gets these. Screen output: $ Please select a dice with 4, 6 or 12 sides: 1356 $ You have entered an incorrect value, please try again $ Please select a dice with 4, 6 or 12 sides:
And then after that? It will ask again "Please select a dice with 4, 6 or 12 sides:", even if I enter 4 at the second prompt :)
@MikeMüller is there anyway of doing with the try: method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.