简体   繁体   中英

logic errors with print the sum of all the numbers that are either multiple of three or five

I'm having some logic errors with my program. I've been trying to solve this for the last couple of hours. It's supposed to print the sum of all the numbers that are either multiple of three or five.

my output

1.)enter an integer number (0 to end): enter an integer number (0 to end):
2.)enter an integer number (0 to end): 3+ = 3

expected output

1.)enter an integer number (0 to end): 3 = 3
2.)enter an integer number (0 to end): 3+5 = 8

below is my code.

while True:
  answer = ""
  num = int(input("enter an integer number (0 to end): "))
  end_answer = 0

  if num == 0:
    exit()

  for i in range(1, num+1):
    if i%3==0 or i%5==0 :
      answer += str(i)
      end_answer += i


    if i != num and (i%3==0 or i%5==0):
      answer += "+"
      print(str(answer) + " = " + str(end_answer) )

I've seen similar answers for this just not in python specifically

The following (properly indented) code will give you what you need:

while True:
    num = int(input('Enter an integer number (0 to end): '))
    if num == 0: exit()

    answer = ''
    end_answer = 0
    sep = ''
    for i in range(1, num+1):
        if i % 3 == 0 or i % 5 == 0 :
            answer += sep + str(i)
            sep = ' + '
            end_answer += i

    if end_answer > 0:
        print(str(answer) + ' = ' + str(end_answer) )

Note that it uses a variable separator sep to more cleanly print the item you're working out. A sample run follows:

Enter an integer number (0 to end): 2
Enter an integer number (0 to end): 3
3 = 3
Enter an integer number (0 to end): 10
3 + 5 + 6 + 9 + 10 = 33
Enter an integer number (0 to end): 38
3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 + 20 + 21 + 24 + 25 + 27 + 30 + 33 + 35 + 36 = 329
Enter an integer number (0 to end): 0

You can simplify your code a lot by using the sum builtin and f-strings for printed text formatting. This will likely be more efficient as well.

Code

from itertools import count

counter = count(1)

while True:
    num = int(input(f'{next(counter)}). Enter an integer number (0 to end): '))

    if num == 0:
        break

    nums = [x for x in range(1, num + 1) if x % 3 == 0 or x % 5 == 0]
    print(f'{" + ".join(map(str, nums))} = {sum(nums)}')

Output

1). Enter an integer number (0 to end): 3
3 = 3
2). Enter an integer number (0 to end): 9
3 + 5 + 6 + 9 = 23
3). Enter an integer number (0 to end): 15
3 + 5 + 6 + 9 + 10 + 12 + 15 = 60
4). Enter an integer number (0 to end): 0

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