“未定义”变量(table_count)但我确实定义了它

时间:2017-11-20 07:39:08

标签: python

def is_int(val):
    if type(val) == int:
        return True
    else:
        if val.is_integer():
            return True
        else:
            return False
mult_tble = float(input("Which multiplication table would you like?: "))
if is_int(mult_tble):
    mult_tble = int(mult_tble)
    print(mult_tble)
else:
    print(mult_tble)
def tble():
    table_count = float(input("How high do you want to go?: ")) + 1
    return table_count
tble()
if is_int(table_count):
    table_count = int(table_count)
    print(table_count)
else:
    print("That is not an integer")
    tble()
print("Here's your table:")
for i in range(1, table_count):
    print(i, " x " + str(mult_tble) + " =", i * mult_tble)`

我运行时的错误消息是:

Traceback (most recent call last):
File "C:/Users/embleton/AppData/Local/Programs/Python/Python36-32/game.py", 
line 20, in <module>
if is_int(table_count):
NameError: name 'table_count' is not defined

我认为我在table_count函数中定义了tble(),但我猜不是。 请帮忙。我是python的noobie,我无法理解这一点。

2 个答案:

答案 0 :(得分:2)

您忘记了tble()的返回值。

再次尝试 -

def tble():
    table_count = float(input("How high do you want to go?: ")) + 1
    return table_count
table_count = tble()
if is_int(table_count):
    table_count = int(table_count)
    print(table_count)

答案 1 :(得分:1)

table_count范围已在def tble()中结束。所以它错误地说没有定义。

因此,请将tble()的返回分配给table_count并进一步使用,如下所示:

table_count = tble()
if is_int(table_count):
    table_count = int(table_count)
    print(table_count)