繁体   English   中英

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

[英]Traceback error: TypeError float object cannot be interpreted as an integer

有人可以帮我弄清楚我的问题吗?

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之间,应该允许我输入小数,但是对于“有多少个大理石”,我希望收到该警告,然后再试一次。

使用is_integer()方法。 如果参数不是整数,则返回布尔值。

例如

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

查看此文档。

您需要字符串的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 <= 100(我的偏好)或范围(0,101)中的x,而不是执行0 <= x和x <= 100。 虽然不推荐第二个:-)

for语句逻辑也有缺陷。 如果用户提供了两个错误的输入,则不会考虑它们。 您在那里也需要一会儿。

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

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

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM