简体   繁体   中英

python Fruitful functions explanation

I'm learning python I couldn't understand what exactly does this piece of code do, its giving an unexpected output. could anyone please explain this please.

#! /usr/bin/python


dx = int(raw_input("ENTER THE VALUE dx:"))
dy = int(raw_input("ENTER THE VALUE dy:"))

def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    print "dx is", dx
    print "dy is", dy
    return 0.0

print distance

Thank you.

It doesn't do anything, because you never call the function. It'll just print the memory address of the function definition, which isn't very useful.

If you did print distance() , you would at least call it, and it would print dx and dy, but then also print 0.0 - because that's what you're returning from the function.

What do you expect it to do?

I assume to mean to call the function, eg print distance(x1, x2, y1, y2) , but this will just result in 0.0 since that is the value you are returning. You also seem to be asking the user for the answers (ie dx and dy ), whereas you need x1, x2, y1, y2 for the function. Without knowing exactly what you expect, here is some code which might do what you want:

def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    print "dx is", dx
    print "dy is", dy

x1 = int(raw_input("ENTER THE VALUE x1:"))
x2 = int(raw_input("ENTER THE VALUE x2:"))
y1 = int(raw_input("ENTER THE VALUE y1:"))
y2 = int(raw_input("ENTER THE VALUE y2:"))

distance(x1, x2, y1, y2)

Well, the first 2 lines of code read two values, dx and dy . Next you define a function whose purpose is to calculate (and probably print AND return) the distance of two points, x1,y1 and x2,y2, but instead it returns 0.0 all the time

In the final statement, you are probably missing the parentheses, since what print distance does is to print some info on the function object, something like <function distance at 0xZZZZZZZZZ> .

A fruitful function is one that returns a value, so probably, what you wanted to do is the following:

px1 = int(raw_input("X1:"))
py1 = int(raw_input("Y1:"))
px2 = int(raw_input("X2:"))
py2 = int(raw_input("Y2:"))

def distance(x1,y1,x2,y2):
    dx = x2 - x1
    dy = y2 - y1
    return dx, dy # return a tuple with the first element being dx and the second dy

print distance(px1,py1,px2,py2)

where I changed the names of input variables so that what the function does is more clear.

Short answer: "fruitful" functions return a value that you can use

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