我是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)
我很困惑,任何帮助将不胜感激!
问题是您没有捕获对的调用结果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)
此外,当你调用ratioFunction(num1, num2)
你的最后一行,这将是一个NameError
除非你有num1
和num2
definied地方。但老实说,这完全没有必要,因为您正在接受输入。该函数不需要参数。另外,在打印时还会出现另一个错误,因为您正在使用+
运算符,ratio12 + '.'
但是它ratio12
是一个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.
虽然有可能,你的函数是假设取参数,你输入的功能外,并把它传递给它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句