Kovacs Eduard
Kovacs Eduard

Reputation: 11

How do I transfer varibles through functions in Python

I am trying to read from keyboard a number and validate it

This is what I have but it doesn't work.

No error but it doesn't remember the number I introduced

def IsInteger(a):
    try:
        a=int(a)
        return True
    except ValueError:
        return False 

def read():
    a=input("Nr: ")
    while (IsInteger(a)!=True):
        a=input("Give a number: ")

a=0
read()
print(a)

Upvotes: 1

Views: 65

Answers (3)

Chris Mueller
Chris Mueller

Reputation: 6680

a is a local variable to the two functions and isn't visible to the rest of your code as is. The best way to fix your code is by returning a from your read() function. Also, the spacing is off in your IsInteger() function.

def IsInteger(b):
    try:
        b=int(b)
        return True
    except ValueError:
        return False 

def read():
    a=input("Nr: ")
    while not IsInteger(a):
        a=input("Give a number: ")
    return a

c = read()
print(c)

Upvotes: 1

Nf4r
Nf4r

Reputation: 1410

I think this is what you are trying to achieve.

def IsInteger(a):
    try:
        a=int(a)
        return True
    except ValueError:
        return False 

def read():
    global a
    a=input("Nr: ")
    while (IsInteger(a)!=True):
        a=input("Give a number: ")

a=0
read()
print(a)

You need to use global expression in order to overwrite the global variable without a need to create return inside the function and typing a = read().

But I would highly recommend u to use the return and re-assigned the value of 'a', as someone stated below.

Upvotes: 1

Nick Delben
Nick Delben

Reputation: 95

It appears as though you are not returning the result of the read() function.

The last line of your read function should be "return a"

And then when you call the read function you would say "a = read()"

Upvotes: 0

Related Questions