2

So I am trying to write a code to find out the if a number is divisible by 3. The steps go like this, enter number, add all digits, if digits greater than 10 add digits together until below 10, see if the digit remaining is 3, 6 or 9 and then print out if it is divisible by 3 or not. Here is my code so far:

user_input = int(input('Enter number: '))
sum = 0
for num in user_input:
    sum += int(num)

    if sum > 10:
        while sum > 10:
            sum = 0
            for num in user_input:
                sum += int(num)

            if sum == 3 or 6 or 9:
                print('Your number is divisble by 3')

            else:
                print('Your number is not divisible by 3')

    else:

        if sum == 3 or 6 or 9:
            print('Your number is divisble by 3')

        else:
            print('Your number is not divisible by 3')

Anyone know how to fix the bug?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Tigre
  • 296
  • 1
  • 14

1 Answers1

1

Replace every:

if sum == 3 or 6 or 9:

With

if (sum in ( 3, 6, 9)):

Also - don't overridesum - it's default function in python, you can name your variable like _sum for instance.

Edit:

IIUC, this is what you're trying to do (you insert multiple numbers delimited by white space initially):

user_input = input('Enter numbers: ').split(" ")

for num1 in user_input:
    sum1 = int(num1)
    if sum1 > 10:
        while sum1 > 10:
            sum_=sum1
            sum1=0
            for num in str(sum_):
                sum1 += int(num)
        if sum1 in (3, 6, 9):
            print(num1, ': Your number is divisble by 3')
        else:
            print(num1, ': Your number is not divisible by 3')

To just get and process single number:

user_input = input('Enter number: ')

sum1 = num1 = int(user_input)

if sum1 > 10:
    while sum1 > 10:
        sum_=sum1
        sum1=0
        for num in str(sum_):
            sum1 += int(num)
    if sum1 in (3, 6, 9):
        print(num1, ': Your number is divisble by 3')
    else:
        print(num1, ': Your number is not divisible by 3')
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34