0
def invInfo():
    initCap = int(input(""))
    invYears = int(input(""))
    return
def invResult():
    if invYears <= 5:
      invPercentage = invYears / 2
      print("")
      return
invInfo()
invResult()

When I input a value in the invYears function and try to use it in the next function, an error occurs saying that the name is not defined. Thanks in advance.

Simon C
  • 11
  • 2
  • 1
    You should read up on [how python resolves names](https://docs.python.org/3/reference/executionmodel.html#resolution-of-names). In other words variable scope. – Jab Sep 20 '19 at 04:01
  • 1
    Possible duplicate of [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – Jab Sep 20 '19 at 04:05

3 Answers3

1

The issue is scope. The variable only exists within the scope that is declared, so in this case you are just declaring it in the first function, it doesn't exist within the second function. If you move the variable declaration up a level (outside of the function) you can access it in both functions

0

Variables cannot be accessed outside of a function. Here is code which will resolve properly as you desire it. So any variables within invInfo stay within invInfo unless you specifically remove them from the function. Using return is one way to do that.

def invInfo():
    initCap = int(input(""))
    invYears = int(input(""))
    return invYears
def invResult(invYears):
    if invYears <= 5:
      invPercentage = invYears / 2
      print("")
      return
invResult(invInfo())
Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35
0
def invResult():
    if invYears <= 5:
      invPercentage = invYears / 2
      print("")
      return

initCap = int(input(""))
invYears = int(input(""))
invResult()

There were issue in scope of variable you should try this hopefully it will work according to your expectations

Vashdev Heerani
  • 660
  • 7
  • 21