回溯错误:TypeError浮点对象不能解释为整数

2024-04-29 10:54:56 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我解决这个问题吗?在

def marbles():
    marbles = 0
    while True:
        try:
            x = eval(input("How many marbles? "))
        except ValueError: 
            print("You can't enter", x , "marbles! How many marbles do you have?")
            continue
        else:
            break
    for i in range(x):
        x = eval(input("Please enter how many marbles between 0 and 100: "))
        if 0 <= x and x <= 100:
            marble = marble + x
        else:
            print("Your number is out of range!")
            y = int(input("Please enter how many marbles between 0 and 100: "))

main()

我似乎不明白为什么当我编码5.4弹珠时,它不会发出警告,你不在射程内。在0到100之间,我应该被允许给出小数,但是对于“多少个弹珠”我想收到警告再试一次。在


Tags: andinputevalrangebetweenelsemanyhow
2条回答

您需要string的isdigit方法。 像这样?在

def marbles():
    marbles = 0
    count_flag = False
    while count_flag is False:
        try:
            x = raw_input("How many marbles? ")
            if not x.isdigit():
                raise ValueError
        except ValueError:
            print "You can't enter %s marbles! How many marbles do you have?" % (x)
        else:
            x = int(x)
            count_flag = True
    for i in range(x):
        x = int(input("Please enter how many marbles between 0 and 100: "))
        if 0 <= x and x <= 100:
            marbles = marbles + x
        else:
            print("Your number is out of range!")
            y = int(input("Please enter how many marbles between 0 and 100: "))

    return marbles

print marbles()

另外,对于python,您可以选择0<;=x和x<;=100,而不是0<;=x<;=100(我的首选项)或范围内的x(0,101)。但不建议使用第二种方法:-)

你的for语句逻辑也有缺陷。如果一个用户给出了两个错误的输入,则不会考虑它们。你也需要一段时间。在

^{pr2}$

老实说,更干净的做法是将输入验证放在另一个函数中,并在marbles函数中调用它。在

def get_number(screen_input):
    flag = False
    while flag is False:
        try:
            x = raw_input(screen_input)
            if not x.isdigit():
                raise ValueEror
        except ValueError:
            print("You can't enter %s marbles! How many marbles do you have?" % (x))
        else:
            return int(x)

def marbles():
    marbles = 0
    x = get_number("How many marbles?")
    while x > 0:
        y = get_number("Please enter how many marbles between 0 and 100:")
        if 0 <= y <= 100:
            marbles += y
            x -= 1
        else:
            print("Your number is out of range!")
    return marbles

print marbles()

使用is_integer()方法。若参数是否为整数,则返回布尔值。在

例如

>>> (5.4).is_integer()
False
>>> (1).is_integer()
True

检查this documentation.

相关问题 更多 >