Mar-09-2021, 12:19 AM
Functions are a way of abstracting some code away, so from the outside of the function you don't have to care about how it does the job, you might just have to hand it some data and get an answer back. From inside the function you don't have to care about when the function is called, just how to get the data from the caller and how to pass it back.
In your function1, it doesn't need any information from the caller, it calls input() directly. But it does produce output (via
In your function1, it doesn't need any information from the caller, it calls input() directly. But it does produce output (via
return
). But in your main code you're not doing anything with the value so it disappears.3 + 4 # valid but useless python. It would compute an answer, but would forget it after ans = 3 + 4 # here the value is stored in a variable for later use function1() # the function may be returning data, but it's not kept. ans = function1() # now we can do something with the info from the function.Same thing when we want to hand data to the function. That's done through the argument list. You've defined function2 to take one argument (which will be seen as
answer
inside the function).answer2() # Error. The function expects one piece of data to arrive. Sending none is not allowed answer2(ans) # We send in the data we got earlier answer2("bogus") # Send in some made-up data answer2("one", "two") # Also an error. We can only send in one piece of data to this function, not less, not more