0

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)
Infusion
  • 17
  • 5
  • No, and that's very well so. Let your function return the value. – Thierry Lathuille May 15 '22 at 18:00
  • No, because the variable *user_variable* does only exist in the scope of *user_value()*. To change variables from different functions, either pass the variable as a parameter to the function or use a global variable. –  May 15 '22 at 18:01
  • Does this answer your question? [Passing an integer by reference in Python](https://stackoverflow.com/questions/15148496/passing-an-integer-by-reference-in-python) – mightyandweakcoder May 15 '22 at 18:03
  • I'm new to coding how would I go about either of those options? @js-on – Infusion May 15 '22 at 18:04
  • See the accepted answer of the post mentioned by @mightyandweakcoder –  May 15 '22 at 18:05

2 Answers2

0

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())
Xanik
  • 365
  • 3
  • 9
0

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
binds
  • 125
  • 2
  • 10