Home > Software design >  python - changing a variable in a function from another function
python - changing a variable in a function from another function

Time:05-16

Is there a way for the function user_message to change the variable user_variable from outside its originating function?

def user_value():
    user_variable = 0
    while user_variable < 1:
        user_variable = int(input("Please enter a value: "))

def user_message():
    user_message = int(input("Please enter a number: "))
    user_value()
    user_variable = user_variable   user_message

user_message()
print(user_variable)

CodePudding user response:

Not really sure exactly what you want to get from the print but I played with it and came up with this solution:

def user_value(user_variable=0):
    while user_variable > 1:
        input_variable = int(input("Please enter a value: "))
        user_variable  = input_variable
        print("New value: "   str(user_variable))


def user_message():
    user_message = int(input("Please enter a number: "))
    user_value(user_message)


print(user_message())

CodePudding user response:

This is where you would use the return statement to return something back to the caller. You would return user_variable and pass it as a parameter to the function you’d like to use it in. Here is an example:

def foo():
    x = 10
    return x

def bar(x):
    # do stuff

Variables declared in functions, and function parameters, are local variables meaning they only exist inside of the scope of the function. A scope block in Python, is determined by the indentation level. Anything under the function signature (def func_name():) and 4 spaces of indentation in is part of the local scope of that function.

# global scope

def foo():
    # foo’s local scope here

# global scope
  • Related