+ 1
How we can use a variable of one function in the other one
the variable's value is entered by the user in one function and I want that value of the variable for the other function please help me def fun1(): a=int(input("value") def fun2(): print(a) will this work
5 Answers
+ 3
declare the variable outside.
+ 3
For what you are trying to do, you can always take the input in function A and pass it to function B as a parameter. There is no need for a global variable to exist.
def func1():
x = input()
func2(x)
def func2(param):
print(param)
func1()
+ 1
example:
value = input('Enter the value: ')
def function_one(a):
# do something with 'a'
print('You entered value %s', % a)
def function_two(a):
# do also something with 'a'
....
# call the function with the value entered by the user
function_one(value)
function_two(value)
+ 1
I would exercise caution with global mutatable variables, global constants are fine, most packages, libraries and programs declare global constants with no adverse side effects. However, global mutables, especially in large programs, can cause "Spaghetti Code".
For testing purposes and smaller programs global variables and global declarations should be fine and easy to trace. However, generally speaking global mutables are typically considered a bad idea and a poor design pattern.
You should "return" the variable, which will allow you to pass it to another.
def thing1():
num=2+2
return num
four=thing1()
print(four)
def thing2(arg):
num=arg + 2
return num
six=thing2(four)
print(six)
0
Declare a global variable, or, as Toni said, declare it oustide.