简体   繁体   中英

"How to use append or extend function using def function in python?"

I am trying to append or extend values by using "def" function, but, I am getting an error numpy.float64 object is not iterable

Basically, I want to store different slopes values in the variable name "all_slope" by using extend or append function. I am passing four different values in call function that is a slope. Would, it possible to help me?

all_slope=[]
def slope(x1,x2,y1,y2):
    x=x2-x1
    y=y2-y1
    slope_value=(y/x)
    all_slope.extend(slope_value)
    return all_slope
slope(3,2,4,2)

Use append instead of extend :

Why:

extend: Extends list by appending elements from the iterable.

append: Appends object at the end.

Read more..

Hence:

all_slope=[]
def slope(x1,x2,y1,y2):
    x=x2-x1
    y=y2-y1
    slope_value=(y/x)
    all_slope.append(slope_value)
    return all_slope

print(slope(3,2,4,2))

OUTPUT:

[2.0]

EDIT:

Good catch by @ mfitzp, Since all_slope is a global var, you could just call the function and then print the list without return :

all_slope=[]
def slope(x1,x2,y1,y2):
    x=x2-x1
    y=y2-y1
    slope_value=(y/x)
    all_slope.append(slope_value)

slope(3,2,4,2)
print(all_slope)

all_slope.extend(slope_value)更改为all_slope.append(slope_value)

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