[英]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.