编写一个计算两个数字之比的函数

新手上路,请多包涵

我是 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 许可协议

阅读 538
2 个回答

问题是您没有捕获调用 int 的结果。

 def ratioFunction(num1, num2):
    num1 = input('Enter the first number: ')
    int(num1) # this does nothing because you don't capture it
    num2 = input('Enter the second number: ')
    int(num2) # also this
    ratio12 = int(num1/num2)
    print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)

将其更改为:

 def ratioFunction(num1, num2):
    num1 = input('Enter the first number: ')
    num1 = int(num1) # Now we are good
    num2 = input('Enter the second number: ')
    num2 = int(num2) # Good, good
    ratio12 = int(num1/num2)
    print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)

Also, when you call ratioFunction(num1, num2) in your last line, this will be a NameError unless you have num1 and num2 definied somewhere.但老实说,这完全没有必要,因为您正在接受输入。此函数不需要参数。 Also, there will be another bug when you print because you are using the + operator on ratio12 + '.' but ratio12 is an int and '.' 是一个字符串。快速修复,将 ratio12 转换为 str

 In [6]: def ratioFunction():
   ...:     num1 = input('Enter the first number: ')
   ...:     num1 = int(num1) # Now we are good
   ...:     num2 = input('Enter the second number: ')
   ...:     num2 = int(num2) # Good, good
   ...:     ratio12 = int(num1/num2)
   ...:     print('The ratio of', num1, 'and', num2,'is', str(ratio12) + '.')
   ...:

In [7]: ratioFunction()
Enter the first number: 6
Enter the second number: 2
The ratio of 6 and 2 is 3.

虽然,您的函数 可能假设接受参数,并且您在函数外部获得输入并将其传递给它。

原文由 juanpa.arrivillaga 发布,翻译遵循 CC BY-SA 3.0 许可协议

def RatioFunctions(num1, num2):
    n1 = float(num1)
    n2 = float(num2)

    return n1/n2

原文由 akmal_quamri 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题