[英]How do you make a function that divides fractions into simplest form python
我正在上課,我很困惑。 如果您能指導我完成此過程並告訴我我做錯了什么,那將真的有幫助。 我有一個與括號有關的錯誤,因為括號中沒有任何內容。 我是新手,對不起。
def FractionDivider(a,b,c,d):
n = ()
d = ()
n2 = ()
d2 = ()
print int(float(n)/d), int(float(n2)/d2)
return float (n)/d / (n2)/d2
您的函數接受參數a
, b
, c
和d
,但是您沒有在任何地方使用它們。 您要定義四個新變量。 嘗試:
def FractionDivider(n, d, n2, d2):
並刪除空括號位,看看是否可以完成您要嘗試的操作。
您無法在執行n =()時聲明變量,然后嘗試為其分配整數或字符串。
n =()並不意味着:
n目前不等於任何值,但我不久將分配一個變量。
()->元組https://docs.python.org/3/tutorial/datastructures.html
它們是序列數據類型的兩個示例(請參見序列類型-列表,元組,范圍)。 由於Python是一種不斷發展的語言,因此可以添加其他序列數據類型。 還有另一種標准序列數據類型:元組。
因此在函數中,如果您希望為varialbes分配作為參數傳遞的內容
例如:
def FractionDivider(a,b,c,d):
n = a
d = b
n2 = c
d2 = d
考慮從上述鏈接中閱讀有關元組的更多信息
n=()
是有效的python語句,因此沒有問題。 但是n=()
將n
評估為一個空的tuple()
。 我相信您想要做的如下。
def FractionDivider(a,b,c,d):
'''
Divides a fraction by another fraction...
'''
n = a #setting each individual parameter to a new name.
d = b #creating a pointer is often useful in order to preserve original data
n2 = c #but it is however not necessary in this function
d2 = d
return (float(n)/d) / (float(n2)/d2) #we return our math, Also order of operations exists here '''1/2/3/4 != (1/2)/(3/4)'''
print FractionDivider(1, 2, 3, 4) #here we print the result of our function call.
#indentation is extremely important in Python
這是編寫相同功能的簡單方法
def FractionDivider_2(n,d,n2,d2):
return (float(n)/d) / (float(n2)/d2)
print FractionDivider_2(1,2,3,4)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.