简体   繁体   English

为什么我的程序无法打印?

[英]Why doesn't my program print?

I'm new to programming and I got stuck. 我是编程新手,但我陷入困境。

I want to write a code which collects the multiples of 3 and 5 in range of 1000 in a list and sum it up. 我想编写一个代码,该代码在列表中收集1000范围内的3和5的倍数并将其求和。 Now I capable to do that in the shell by writing: 现在,我可以通过编写以下代码在shell中执行此操作:

numbers = []

for number in range(1001):
  if number%3 == 0 or number%5 == 0:
    numbers.append(number)

sum (numbers)

and it gives me the answer 234168 so this works, however, if I write this in to file: 它给了我答案234168,所以这可行,但是,如果我将其写入文件:

def multiples():
 numbers =[]
 for number in range(10):
  if number%3 == 0 or number%5 == 0:
      numbers.append(number)
  sum (numbers)


multiples()

then in the shell python will inform me that the code ran, but doesn't give me back anything! 然后在shell中python会通知我代码已经运行,但是什么也没给我! I tried using print, removing spaces, relocating the lines but it just doesn't give me back the result.(not even an error message) 我尝试使用打印,删除空格,重新定位行,但这只是没有给我返回结果(甚至没有错误消息)。

Please help me because this drives me crazy and I would like to apologize for any writing mistakes since English is not my native language. 请帮助我,因为这使我发疯,对于任何书写错误,我深表歉意,因为英语不是我的母语。

def multiples():
  numbers = []
  for number in range(10):
    if number % 3 == 0 or number % 5 == 0:
      numbers.append(number)

  return sum(numbers)

print (multiples())

output: 输出:

23

You need to return the sum of the numbers in your multiples function. 您需要返回multiples函数中数字的总和。 Try it with a function looking like this: 尝试使用如下所示的函数:

def multiples():
  numbers =[]
  for number in range(10):
    if number%3 == 0 or number%5 == 0:
      numbers.append(number)
  return sum(numbers)

When you ran your code step by step in the python shell, the shell always prints the result of the last statement, so it printed what the sum(numbers) statement calculated. 当您在python shell中逐步运行代码时,shell始终会打印最后一条语句的结果,因此它将打印计算出的sum(numbers)语句。 When using a function, you need the return statement ( Python Docs: Return Statement ) in order to pass values to the calling scope of the function. 使用函数时,您需要return语句( Python Docs:Return Statement )以便将值传递给函数的调用范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM