2

I am not an expert of defining function but I would need to create a new one.

I have one function

  • where I enter manually a query;
  • where I set parameters like language and country;
  • then the last function where I should pass all these parameters as fields.

Since the functions that I am using are too big to be reported here, I will give you an example:

def fun1():
   query=input("Enter query:")
   return (query)

def fun2():
   country=input("Enter country:")
   language=input("Enter language:")
   return(country, language)

def fun3():
    
     fun1()
     fun2()
     print("Country: You have selected ",country)
     print("Language: You have selected ", language)
     print("Query: You have selected ", query)

This does not recognise country, language and query from the previous functions. Can you explain me how to correctly define the last functions in order to use the parameters previously set?

2 Answers2

1

Here is how:

def fun1():
    query = input("Enter query: ")
    return query

def fun2():
    country = input("Enter country: ")
    language = input("Enter language: ")
    return country, language

def fun3():
    
    query, (country, language) = fun1(), fun2()
    print("Country: You have selected", country)
    print("Language: You have selected", language)
    print("Query: You have selected", query)
    
fun3()

Input:

Enter query: Are you happy?
Enter country: Australia
Enter language: English

Output:

Country: You have selected Australia
Language: You have selected English
Query: You have selected Are you happy?
Red
  • 26,798
  • 7
  • 36
  • 58
0

When you call the functions they set query, country, and language within their own scopes. The query is owned by fun1(), and country and language are owned by fun2().

When these functions are done running, query, country, and language go out of scope and are no longer valid.

Since you are returning the values of these variables, fun3() should capture the results.

The correct way to do what you are trying is:

def fun3():
     query = fun1()
     country, language = fun2()
     print("Country: You have selected ",country)
     print("Language: You have selected ", language)
     print("Query: You have selected ", query)
Mike Organek
  • 11,647
  • 3
  • 11
  • 26