-3

I have an assignment. It was suppose to do the following: --> Take an integer input(say 100) --> Add the digits till the sum is a single digit number(1)

My program till now is:

goodvalue1=False
goodvalue2=False

while (goodvalue1==False):
    try:
        num=input("Please enter a number: ")
    except ValueError:
        print ("Wrong input. Try again.")
    else:
        goodvalue1=True


if (goodvalue1==True):
    ListOfDigits=list(map(int,str(num)))
    sum=10
    while(sum>9):
        Sum=sum(ListOfDigits)
        if (Sum>9):
            ListOfDigits=list(map(int,str(Sum)))
            Sum=sum(ListOfDigits)
suspectus
  • 16,548
  • 8
  • 49
  • 57
Abhirup Ghosh
  • 29
  • 1
  • 7
  • 2
    Well, what's the issue? – Rohit Jain Jul 22 '13 at 12:26
  • Some thoughts: you don't need to check `if (something == True)`, just do `if something`. For your while loop, you can do `while not goodvalue1`. Also, you don't need the parentheses in your if and while conditions. Don't use variables that shadow built-in functions (ie `sum`). Don't have your variables capitalized to start - good style has vars start lowercase and classes start uppercase. I highly recommend taking a look at the [Python style guide](http://www.python.org/dev/peps/pep-0008/#introduction). – thegrinner Jul 22 '13 at 12:32

4 Answers4

3

Those booleans are not needed. You can factor the code down to:

while True:
    try:
        num = int(input("Please enter a number: ")) # Note how I've added int()
        break # Breaks out of the loop. No need for a boolean.
    except ValueError:
        print("Wrong input. Try again.")

I don't see why you called list(map(int, str(num))); but I think you were intending to put int() around your input. So I added one in above. Now it can catch an error :).

Now, to get one digit, you can use another while loop here:

while num > 9:
    num = sum(map(int, str(num)))

Pretty much this creates [1, 0, 0] which sum() then calls on. This repeats until it is no longer a two digit number (or three, four, etc)

So altogether:

while True:
    try:
        num = int(input("Please enter a number: ")) # Note how I've added int()
        break # Breaks out of the loop. No need for a boolean.
    except ValueError:
        print("Wrong input. Try again.")

while num > 9: # While it is a two digit number
    num = sum(map(int, str(num)))

Just note that for conditional statements, it's never pythonic to do a == True or b == False.

From the PEP:

Don't compare boolean values to True or False using ==.

Yes: if greeting:

No: if greeting == True:

Worse: if greeting is True:

Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
1

You're very close. Here's what you need to change:

Sum=sum(ListOfDigits)
while(Sum>9):
    Sum=sum(ListOfDigits)
    if (Sum>9):
        ListOfDigits=list(map(int,str(Sum)))
        Sum=sum(ListOfDigits)

In this code, you have a while loop that executes when sum is bigger than 9. So why use another variable Sum (also, it makes for really difficult-to-read code)? Do this instead:

while(sum>9):
    sum=sum(ListOfDigits)
    ListOfDigits=list(map(int,str(sum)))

This is only to show you what went wrong with your code. I wouldn't recommend using it (look below for what I would do). First, you mix variable-naming conventions, which is a very bad idea, especially when you work in a team (even otherwise, can you imagine looking at your code a month or six months from now?).
Second, you don't ever use goodvalue2; what's it there for?
Third, if goodvalue1 is only ever going to be a bool, then why check if (goodvalue1==True)? if goodvalue1 is clearer and more pythonic.
Please, for the love of all that is good, use some spaces in your code. Eyes get very strained after looking at expressions like ListOfDigits=list(map(int,str(num))) for a while. Try ListOfDigits = list(map(int, str(num))) instead.

Personally, I would do this:

num = None
while num is None:
    try:
        num = int(raw_input("Enter a number: "))
    except ValueError:
        num = None

num = sum(int(i) for i in str(num))
while num > 9:
    num = sum(int(i) for i in str(num)) # this uses a list comprehension. Look it up, they're very useful and powerful!
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • This code is horrible Python but still correct, why the downvote? – dav1d Jul 22 '13 at 12:29
  • @dav1d: thank you. I was wondering the same thing – inspectorG4dget Jul 22 '13 at 12:30
  • 1
    @dav1d: try running it, then come back and tell us how correct it is. It tries to call a builtin function that's been shadowed by a local variable, and suggests undoing the part of the code that kind of sort of attempted to stop shadowing it (granted, unsuccessfully) by changing capitalization. – Wooble Jul 22 '13 at 12:31
  • @Wobble I take back what I said, I only saw the idea behind this non-python idomatic code. Of course this can't run. – dav1d Jul 22 '13 at 12:34
  • @Wooble: fair point. I just fixed that. This is one of the reasons I hate capitalization based variable separation – inspectorG4dget Jul 22 '13 at 12:39
  • @RussW: thanks for the bug report. Would it be too much to ask SO for code refactoring support? – inspectorG4dget Jul 22 '13 at 12:50
1

My take on this:

inp = None
while inp is None:
    try:
        inp = int(input('Enter number here: '))
    except ValueError:
        print('Invalid Input, try again')

summed = sum(map(int, str(inp)))
while summed > 9:
    summed = sum(map(int, str(summed)))

print('The result is {}'.format(summed))

For an explanation @Haidro did a good job: https://stackoverflow.com/a/17787707/969534

Community
  • 1
  • 1
dav1d
  • 5,917
  • 1
  • 33
  • 52
-1

RECURSION !

Calculate the sum of the digits. Check if the sum has one digit or multiple digit. If one digit, that is your answer, else, call the function on the sum again.

def oneDigitSum(n):
    if n < 10:
        return n
    else:
        return oneDigitSum(sum([int(i) for i in str(n)]))
        # [f(elem) for elem in li] = [f(a), f(b), .... ] where li = [a, b, ... ]
        # sum returns the total of the numbers in list

while True: # continue this loop for eternity, until it gets break
    try:
        num=int(input("Please enter a number: "))
        print(oneDigitSum(num))
        break # printed the sum, now I can break the loop peace fully
    except ValueError:
        print ("Wrong input. Try again.")
        continue # oops, looks like wrong input, lets continue the loop
rnbguy
  • 1,369
  • 1
  • 10
  • 28