[Tutor] Print result of function doesn't work
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Jul 21 20:37:43 EDT 2024
On 21/07/2024 17:06, Torbjorn Svensson Diaz via Tutor wrote:
>> You do know that you can put the prompt inside the input()?
>>
>> leg1 = input("What is the length of the first leg of the triangle?")
>
> Yes, "3" as leg1 and "4" as leg2.
That would be thevalues you input as a result of the prompt.
I was merely pointing out that you don;t need a separate
print() line, you can put the prompt string inside the input() call.
>>> def hypotenuse(leg1, leg2):
>>> legs = leg1**2 + leg2**2
>>> result = math.sqrt(legs)
>>> return result
>>>
>>> x = hypotenuse
>> I suspect the line where you assign x looks different.
>
> >>> import math
>
> >>> def hypotenuse(leg1, leg2):
> ... legs = leg1**2 + leg2**2
> ... result = math.sqrt(legs)
> ... return result
> ...
> >>> hypotenuse(3, 4)
> 5.0
notice you are
a) not assigning the result to x before printing.
and
b) providing parameters to hypotenuse()
> (define (hypotenuse leg1 leg2) (sqrt (+ (expt leg1 2) (expt leg2 2))))
> (display (hypotenuse 3 4))
Yes, but again there is no intermediate assignment to x.
The programs are not equivalent.
>> (hypotenuse)
>>
>> Can you see what's missing?
>
> The parameters of the function? Is that what you mean?
Exactly. The function name by itself evaluates to a function
object(just as it would in Lisp/scheme). You must provide
the parameters inside parens for Python to execute the function.
In fact its the parens that cause the execution, you need
them even if there are no arguments.
> If i write like this
>
> import math
>
> print("What is the length of the first leg of the triangle?")
> leg1 = input()
input() reads a string from the user. You should convert
it to an int/float before using it.
>
> print("What is the length of the second leg of the triangle?")
> leg2 = input()
>
> def hypotenuse(leg1, leg2):
> legs = leg1**2 + leg2**2
This should give a type error because you are passing strings
not ints(or floats).
> result = math.sqrt(legs)
> return result
>
> x = hypotenuse(leg1, leg2)
> print(x)
>
>
> it still doesn't work.
If you fix the type errors it should be ok.
--
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