在学校我们必须写一个程序来运用毕达哥拉斯的理论。我是用python3写的,但是当我返回cber时,程序就结束了。另一方面,bber工作正常。有人能帮忙吗?已经谢谢了:)
编辑:谢谢你的帮助,这并不是kiezen函数的全部,用户可以选择两个数字,j和n决定它们在三角形中的哪条线,也就是kiezen函数。这是一个叫做cijfers的函数,我不知道这是否有区别。我使用return是因为如果用户输入了无效的数字,我可以让他/她重新选择数字。我忘了在发布之前删除cber中的ifs。我会尽力的 尽快改进我的程序。感谢您的反馈:)
def bber():
if (c >= a):
print(str(a) + "^2 + b^2 = " + str(c) + "^2")
print("b^2 = " + str(c) + "^2 - " + str(a) + "^2")
print("b = V(" + str(c**2) + " - " + str(a**2) + ")")
print("b = V" + str((c**2) - (a**2)) + " = " + str(math.sqrt((c**2) - (a**2))))
if (a >= c):
print("De rechthoekzijde kan niet langer zijn dan de schuine zijde.")
cijfers()
def cber():
if (a >= b):
print(str(a) + "^2 + " + str(b) + "^2 = c^2")
print("c^2 = " + str(a) + "^2 + " + str(b) + "^2")
print("c = V(" + str(a**2) + " + " + str(b**2) + ")")
print("c = V" + str((a**2) + (b**2)) + " = " + str(math.sqrt((a**2) + (b**2))))
if (b >= a):
print(str(a) + "^2 + " + str(b) + "^2 = c^2")
print("c^2 = " + str(a) + "^2 + " + str(b) + "^2")
print("c = V(" + str(a**2) + " + " + str(b**2) + ")")
print("c = V" + str((a**2) + (b**2)) + " = " + str(math.sqrt((a**2) + (b**2))))
def kiezen():
x = int(input("Wat is de lengte van de eerste zijde?"))
xz = input("Is deze zijde een rechthoekzijde (J/N)?")
print(" ")
y = int(input("Wat is de lengte van de tweede zijde?"))
yz = input("Is deze zijde een schuine zijde (J/N)?")
print(" ")
return kiezen()
if xz == "j" or "J":
if yz == "n" or "N":
b = y
a = x
return cber()
if yz == "j" or "J":
c = y
a = x
return bber()
有一些问题正在发生。你知道吗
在代码中,您使用的是
math.sqrt
,因此第一行需要实际导入文件开头的math
模块:您无法访问函数中的变量。要将它们传递给函数,必须将它们指定为函数参数:
定义bber(a,c):
从积极的方面来看,函数
bber
在语句if (c >= a)
中报告了正确的答案。但是,下面的条件语句if (a >= c)
调用函数cijfers()
,而函数实际上并不存在。在这种情况下,每当a大于或等于c时,程序将打印NameError
。你知道吗cber
起作用,但实际上不需要有if
语句,因为无论b大于a或a大于b都可以得到变量c。不过,您可能需要考虑检查其他类型的输入(如文本、负数、浮点等)。你知道吗下面是如何简化
cber
函数,同时还必须传入实际参数:函数
kiezen
实际上没有在代码中执行任何操作。它是有定义的,但显然你不在任何地方使用它。函数内部定义的变量是该函数的局部变量,而函数外部定义的变量(即无缩进)是全局变量。当需要在函数中使用全局变量时,必须将其作为函数参数传递。有关此主题的更多信息,您可以阅读“范围”、“全局范围”和“局部范围”的概念。您还可以在官方Python文档here中找到示例。
现在,为了让您了解如何使用全局定义的变量,我将使用不完整的
kiezen
函数,而不实际将其变为函数,因此代码将直接在程序中执行。你知道吗return
,因为这就是它的含义:返回函数的结果。你知道吗这意味着您必须通过删除return关键字来更改代码
return cber()
和return bber()
。你知道吗您的问题末尾缺少一个空格
input
。键入答案时,它将出现在字符串中最后一个字符的旁边。当您想要检查多个选项时(就像您对
XZ == "j" or "J"
所做的那样),您可以改用列表和关键字。下面是一些需要的修改,以使您的程序最终工作。注释出现在带有#符号的行上。你知道吗
正如我前面提到的,这并不完美,因为您需要管理错误。例如,如果输入文本而不是数字,它将不起作用,但这是另一个讨论的主题。你知道吗
此外,在本练习中,如果您的目标只是打印输出,则实际上不需要在函数中使用
return
关键字,但请记住,如果您需要重用函数的结果,则必须为其返回一个值。你知道吗这一概念的一个简单例子如下:
相关问题 更多 >
编程相关推荐