这个Python代码有什么问题?拒绝输入

这个Python代码有什么问题?拒绝输入,python,Python,每次我输入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 (n

每次我输入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: ")

在Python3中,当使用
input()
时,它返回一个字符串。因此,您将有类似于
“4”
的内容。而且
“4”不是4

因此,在您的脚本中,特别是在[4,6,12]中的
if边数处,它将始终是
False
,因为您在[4,6,12]
中真正说的是
if“4”(我只是以4为例)

将字符串转换为整数:

>>> int("4")
4

看起来您正在尝试确定是否提供了输入<不需要代码>len(…)==0
。如果边数,你可以说
。因为空字符串是
False
,如果输入了空字符串,则不会执行if语句



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


其他一些小事情:

  • .lower()
    不会对字符串进行适当排序,因为字符串在python中是不可变的。您可能只想将
    .lower()
    附加到
    输入()的末尾

  • 您可能还希望在第二次输入时使用
    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!")
    

海德罗给了你理由,但这里有一种不同的方法来解决你的问题:

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!')

您应该更改脚本,如下所示

这是重要的部分:

    try:
        number_of_sides = int(input("Please select a dice with 4, 6 or 12 sides: "))
    except ValueError:
        wrong = True
使用
int(input(“…
)在输入时正确转换为
int
。如果用户输入任何无法转换为整数的内容,Python将引发
ValueError
。您可以捕捉到这一点,显示一条消息,然后使用
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()

即使它是一个整数,对它调用len()也不起作用。也许它应该是['4','6','12']中的
n
number\u of_sides==int
也会始终返回
False
@UlrichEckhardt,或者在[4,6,12]中返回
if int(number\u sides)]
,但你完全正确。是的。有太多的错误不起作用。OP应该采取更小的步骤和/或将代码减少到可能的最小部分,使其不符合预期。哦,说准确的错误和期望也有帮助。如果我做
int(输入(“请选择一个有4面、6面或12面的骰子:“)
OP使用的是python 3,我根据语法推测。所以
print()
而不是
print
:)严格来说
print()
也可以在Python 2.7中使用,但您可能是对的。此外,这看起来非常干净。我正在对此进行升级。这里的逻辑需要一些工作。Conder在第一个while循环中,有人输入了“1356”;会发生什么?1356不在
[2,4,6]
因此
其他
获取这些。屏幕输出:$
请选择一个4面、6面或12面骰子:1356
$
您输入的值不正确,请重试
$
请选择一个4面、6面或12面骰子:
然后,它会再次询问
“请选择一个4面、6面或12面骰子:“
,即使我在第二次提示时输入了
4
:)@MikeMüller是否可以使用
try:
方法我不确定它如何接受任何值<代码>边数不能同时是4、6或12中的一个,也不能同时是长度为0的字符串。在任何情况下,您都不能输入与类型
int
相等的字符串。别忘了接受答案!:)
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()