我目前在我的第一门编程课上,必须创建一个返回两个数字之和的函数。运行以下代码时出现错误。它似乎与我的打印声明有关,但可能还有其他我缺少的东西。我想了解一下,因此我们将不胜感激!
first_number = input("Enter first number: ")
second_number = input("Enter second number: ")
def sum_between(first_number, second_number):
while first_number <= second_number:
sum_between_numbers = range(first_number, (second_number +(str(1)))
print(sum_between_numbers)
答案 0 :(得分:0)
一个返回两个数字之和的函数:
def sum(first, second):
return first + second
返回这两个数字之间的所有数字之和的函数
def sum_between(first, second):
nums_between = range(first, second+1) # Generates a list [first, first+1, first+2, ..., second]
sum_between = 0 # initialize the sum between as 0
for num in nums_between: # count through every number from first to second...
sum_between += num # ...and add them together
return sum_between # return the sum of all of that
更Python化的方法是使用内置函数sum()
,该函数可以进行任何迭代,并返回其中所有项的总和:
def sum_between(first, second):
nums_between = range(first, second + 1)
return sum(nums_between)
然后,您只需要调用您的代码:
first_number = int(input("Enter first number: ")) # the input() function returns a string; we need to typecast it to an integer first
second_number = int(input("Enter second number: "))
...
print(sum_between(first_number, second_number))
请记住,python不是javascript。 Python关心两种类型是什么,并且,如果您尝试将int
和str
加在一起,则可能会出错。整数加法如下:
1 + 2 == 3
字符串加法(称为“串联”)的工作原理如下:
'1' + '2' == '12'
这是您在代码中遇到的问题的一部分-我将留给您调查它发挥作用的地方。良好的学习锻炼。