我是 Python 编码的新手,所以请记住以下问题。我只是在学习定义函数、参数和变量的用法。
定义一个名为 ratioFunction 的函数,它以两个名为 num1 和 num2 的数字作为参数并计算这两个数字的比率,并将结果显示为(在此示例中 num1 为 6,num2 为 3): ‘6 和 3 的比率为2’。运行代码后的输出应如下所示:
Enter the first number: 6
Enter the second number: 3
The ratio of 6 and 3 is 2.
所以这就是我用我有限的编码知识和我对函数的完全困惑编造的东西:
def ratioFunction(num1, num2):
num1 = input('Enter the first number: ')
int(num1)
num2 = input('Enter the second number: ')
int(num2)
ratio12 = int(num1/num2)
print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)
我很困惑,任何帮助将不胜感激!
原文由 NBowman6 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是您没有捕获调用
int
的结果。将其更改为:
Also, when you call
ratioFunction(num1, num2)
in your last line, this will be aNameError
unless you havenum1
andnum2
definied somewhere.但老实说,这完全没有必要,因为您正在接受输入。此函数不需要参数。 Also, there will be another bug when you print because you are using the+
operator onratio12 + '.'
butratio12
is anint
and'.'
是一个字符串。快速修复,将ratio12
转换为str
:虽然,您的函数 很 可能假设接受参数,并且您在函数外部获得输入并将其传递给它。