Reputation: 15
i want to get the insert() function data in find() function.
n=int(input("Enter choice: "))
if n==1:
def insert():
data=['oop','java','python']
print(data)
return data
insert()
elif n==2:
def find():
data.insert(1,"hi")
print(data)
find()
after pressing 2 final output should be
['oop','hi','java','python']
Upvotes: 0
Views: 451
Reputation: 574
Try this -
n=int(input("Enter choice: "))
data = ['oop', 'java', 'python']
if n==1:
def insert():
print(data)
return data
insert()
elif n==2:
def find():
data.insert(1,"hi")
print(data)
find()
Output - ['oop', 'hi', 'java', 'python']
To use list locally:
n = int(input("Enter choice: "))
def insert():
data = ['oop', 'java', 'python']
return data
def find():
data = insert()
data.insert(1, "hi")
return data
if n==1:
print(insert())
elif n==2:
print(find())
Output:
>> Enter choice: 2
['oop', 'hi', 'java', 'python']
>> Enter choice: 1
['oop', 'java', 'python']
Upvotes: 1
Reputation: 88
EDIT: I didn' read your desired output.
Not sure if this is what you need:
n=int(input("Enter choice: "))
def insert():
data=['oop','java','python']
print(data)
return data
def find():
def find():
data_func = insert()
data_func.insert(1, "hi")
print(data_func)
if n==1:
insert()
elif n==2:
find()
You can't declare funcions inside a conditional "if" since if your input is 2 you will never execute inset() funcion and data variable will never be declared.
Also you should name your functions in different way from python predefined methods...
regards.
Upvotes: 1
Reputation: 66
You need to understand how scope works in Python. You can read about it here https://realpython.com/python-scope-legb-rule/ but a basic understanding is that variables declared in a function is only local to that function. What you probably need to do is to pass the data array to both functions to Keep the scope of the variable.
Upvotes: 0