0

每次我输入 4、6 或 12 时它都不接受它。为什么?代码对我来说看起来不错。请告诉我如何纠正或改变什么。

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: ")
4

3 回答 3

7

在 Python 3 中,当使用 时input(),它返回一个字符串。因此,您将拥有类似"4". 和"4" is not 4

所以在你的脚本中,特别是在if number_of_sides in [4,6,12],它总是False,因为你真的在说if "4" in [4,6,12](我只是在做 4 作为例子)。

将字符串转换为整数:

>>> int("4")
4

看起来您正在尝试确定是否给出了输入。len(...) == 0不需要。你可以说if number_of_sides。因为一个空字符串是False,并且如果输入了一个,那么 if 语句将不会执行。


此外,number_of_sides == int这不是检查对象是否为整数的方法。使用isinstance()

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

其他一些小事:

  • .lower()不对字符串进行就地排序,因为字符串在 python 中是不可变的。您可能只想附加.lower()input().

  • 您可能还想while为第二个输入使用循环。观察:

    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!")
    
于 2013-06-08T11:46:37.160 回答
2

Haidro 给了你原因,但这里有一种不同的方法来解决你的问题:

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!')
于 2013-06-08T11:58:18.783 回答
0
于 2013-06-08T12:05:16.710 回答