简体   繁体   中英

How to return an input within a def function with python

I'm new to python and defining functions!

I'm writing a code and, on it, I'll sometimes ask the same question, this is why I want to use a function for it. I'm trying like this:

def cont():
  ans = input("Continue? ")
  return ans

But it's not storing anything on ans, cause every time I call it, I get an error saying that ans has not been declared!

Could anybody help me?

There's nothing wrong with your function. Here's an example:

def cont():
    ans = input("Continue? ")
    return ans


for i in range(2):
    print(cont())

Output:

Continue? y
y
Continue? n
n

If you need to use it in an if-statement :

for i in range(3):
    result = cont()
    if result == 'y':
        print('yes')
    elif result == 'n':
        print('no')
    else:
        print("I don't understand")

Output:

Continue? y
yes
Continue? n
no
Continue? p
I don't understand

However, if you don't plan on expanding the cont() function, and doing something more complex with it, as it is now, it's pretty useless because you can simply use input("Continue? ") wherever you use cont() .

Your ans is only defined inside the scope of your cont() function, you cannot access it directly from outside that function. You are most of the way to sending this ans back out to the rest of your code with return ans , now you just need to store that value in something you can access from the rest of your code. Here is a sample code where I saved the output of cont() in the variable check in each pass of a while loop.

def cont():
    ans = input("Continue? ")
    return ans

gonna_continue = True

while gonna_continue:
    check = cont()
    if check == "no":
        gonna_continue = False
print("All Done")

SAMPLE OUTPUT

Continue? 1
Continue? 2
Continue? 5
Continue? sbdj2
Continue? no
All Done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM