0

I'm really new to python or programming in general.

I am trying to make a function that draws input from the user and check if it is an integer.

However, after checking that the input is an integer, I am unable to use the variable outside of the loop, with an error message shown below:

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}.")
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
rcshon
  • 907
  • 1
  • 7
  • 12

1 Answers1

1

You need to return the value of b from function to be used outside the function:

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 ' )
Sociopath
  • 13,068
  • 19
  • 47
  • 75