如何分配要在循环外部使用的变量?

时间:2018-08-04 10:55:09

标签: python scope

我对python或程序设计真的很陌生。

我正在尝试创建一个从用户处提取输入并检查它是否为整数的函数。

但是,在检查输入是否为整数之后,我无法在循环外使用变量,并显示以下错误消息:

python3.7 new.py 
How much is your balance in your account?
>123
Traceback (most recent call last):
File "new.py", line 14, in <module>
print(f"Thank you, your account balance is {b}.")
NameError: name 'b' is not defined



def inputintegertest():
    while True:
        try:
            a = int(input(">"))
            b = "${:.2f}".format(a)
            break
        except ValueError:
            print("Please enter a number.")

print("How much is your balance in your account?")

inputintegertest()

print(f"Thank you, your account balance is {b}.")

1 个答案:

答案 0 :(得分:1)

您需要从函数中返回b的值以在函数外部使用:

def inputintegertest():
    while True:
        try:
            a = int(input(">"))
            b = "${:.2f}".format(a)
            return b
        except ValueError:
            print("Please enter a number.")


print("How much is your balance in your account?")

b = inputintegertest()

print(f"Thank you, your account balance is {b}.")

print('Welcome ' )