简体   繁体   中英

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. Now I capable to do that in the shell by writing:

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:

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! 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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