2016-04-24 60 views
0
def quadratic_roots(a,b,c): 
     if not (type(a)==int or type(a)==float) and (type(b)==int or type(b)==float)\ 
    and (type(c)==int or type(c)==float): 
    print("Error. Must be numbers.") 
    return None 
equation=(b**2)-(4*a*c) 
realRoots=[] 
if equation<0: 
    return realRoots 
elif equation==0: 
    x1=-b/(2*a) 
    #realRoots.append(x) 
    return [x1] 
else: 
    x1=(-b+((equation)^(1/2))/(2*a) 
    x2=(-b-((equation)^(1/2))/(2*a) 
    return realRoots.append(x1,x2) 

我需要將我的二次方根放入列表中,但我不斷收到語法錯誤。我如何編輯我的代碼,以便它能正常工作?將二次方根置於列表中

回答

1

append只需要一個參數,並返回Nonedocumentation):

return realRoots.append(x1,x2) # cannot work 

# Instead, either `append` one by one: 
realRoots.append(x1) 
realRoots.append(x2) 
return realRoots 

# or use 'extend': 
realRoots.extend([x1, x2]) 
return realRoots 

# or the simplest 
return [x1, x2] 

順便說一句,在「power'運營商在Python是**,不^

> 2**3 
8 

> 2^3 
1 
0

正如@schwobaseggl所述,您必須更改權力運算符和附加語法。 還注意到追加方法不會返回任何值(默認爲無) so return realRoots.append(x1) add x1 to realRoots但返回None