[Tutor] function question

Alan Gauld alan.gauld at yahoo.co.uk
Sat Jan 5 12:24:19 EST 2019


On 05/01/2019 16:18, David Lynch wrote:
> Hello,
> I'm not sure if this is where I can find this sort of help but I am
> struggling understanding functions. I have written a simple math code but I
> feel like it could be improved if I were to use it in a function.

You arein the right place and you have the right idea.

You might find my tutorial on functions worth looking at:

http://www.alan-g.me.uk/l2p2/tutfunc.htm

But for the short version keep reading...


> From what I've read about functions I should be able to define a function
> with 2 variables? And then I can add all of my code into that function by
> indenting it.

That's correct, more or less.

So a function with two variables will look like

def aFunction(var1,var2):
     your code here
     return result

>  And then shouldn't I be able to
> function(float(input("enter input: ")))

No because you are only passing one variable into the
function - the result of the input)() function.
input() is just a function like any other, it
takes an input parameter and returns a value.


> function(float(input("enter input 2: ")))

And again you call your function with a single value.
The function has no memory of previous calls so it
won't know about your previous attempt with input

> return(function)

And the return statement needs to be inside the
function. It returns the resuilt to the caller
of the function.

So you really want something like

result = function(input('Value1'), input('Value 2'))

Although we generally consider using input like that
a bad idea. It would be better to write:

val1 = input('Value 1')
val2 = input('value 2')
result = function(val1,val2)

It's slightly longer but much easier to debug if
things go wrong!

> Also, since it'll be in a function, when I type return(function) will it
> rerun the code from the top?

Every time you type function() it will run the
function code afresh.

To try to clarify things, here is a very simple
function that simply adds two numbers and the
code that uses it.

def add(val1,val2):
    total = val1 + val2
    return total

x = int( input('Val1? ') )  # convert input string to integer
y = int( input('Val2? ') )
result = add(x,y)
print(x, '+', y, '=', result) #or print("%d + %d = %d" % (x,y,result))

See my tutorial paqe for more examples and a more
complete explanation.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list