Https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/digitsum?action=lesson_resume


#1

To all

I am having some trouble with the python lesson: Practice Makes Perfect- exercise 4. I created a code which I was looking to define as digit_sum. This code should allow me to take a positive integer n as input and return the sum of all that number’s digits. For example, digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. My code, when implemented in IDLE undefined (see version 1), works fine and achieves the objective. However when formatted as a user-defined function in (see version 2), I am unable to achieve the same results I know there are easier ways to achieve the objectives by completely re-writing my function but I was hoping to understand why the second version was not able to run as expected and what I am lacking in my understanding of the capabilities of user-defined function.

version 1

n=434
number = []  
while n>0:
           
        if n %10 != 0 and n>10:
            number.insert(0,n%10)
            n = int((n - n%10)/10)
            print(number)
        elif n <= 10 and n - int(n) == 0:
            number.insert(0,n)
            print(number)
            n=sum(number)
            break
        
print (n )    

version 2

many thanks in advance


#2

everything which needs to be in the function body, should be properly indented, look:

def example():
    print('i am inside the function')

print('i am outside/after the function')

so, knowing this, the only thing your function does, is defining an array


#3

thanks for your reply,I have implemented the advice how would I look to add the return in the code below so that I can obtain the sum which is the value of (n).

def digit_sum(n):
	number =[]	  
	while n>0:
		if n %10 != 0 and n>10:
			number.insert(0,n%10)
			n = int((n - n%10)/10)
			print(number)
		elif n <= 10 and n - int(n) == 0:
			number.insert(0,n)
			print(number)
			n=sum(number)
 			break

#4

well, after the loop we want to return the sum, in which variable did you store the sum? this is what you should return outside/after the loop


#5

i stored the stored the sum in the variable n in previously made attempts to add the return with various indentations but was unable to get the expected answer



def digit_sum(n):
	number =[]	  
	while n>0:
		if n %10 != 0 and n>10:
			number.insert(0,n%10)
			n = int((n - n%10)/10)
			print(number)
		elif n <= 10 and n - int(n) == 0:
			number.insert(0,n)
			print(number)
			n=sum(number)
            print (n)
            break (n)
 		return (n)

#6

Use 4 spaces as indentation. Nothing else. Especially do not mix tabs and spaces. The bodies of statements such as functions and loops are indented once (4 spaces) and you deindent once to exit (-4 spaces). That’s all there is to it.

Do not shuffle your indentation around. It has meaning, when you speak, you have to know what you say, you don’t scramble words around without a plan. If you don’t know where something goes, then you need to take the time to understand what you’ve written so that you can reason out where that something should be placed.

for n in range(3):
    print 'this message gets printed 3 times'
print 'this one only gets printed once'

#7

I was trying to get across that from what I understand I am trying to return the value of n from the defined function. This means that I should have one indentation from the initial state of the function. That didn’t work so then I tried several attempts with different indentations. I am at the point where though I have read into functions I have misunderstood something about the use of user-defined functions. So how can I change the function shown to return the value of n that I expect? NOTE: I have got the code to work when it is not being user-defined I just don’t know why it won’t work when it is user-defined


def digit_sum(n):
	number =[]	  
	while n>0:
    #loops until the statement is no longer true 
		if n %10 != 0 and n>10:
      #insert a value of n to the begining of an array 
			number.insert(0,n%10)
      #determine a new value of n for the next iteration
			n = int((n - n%10)/10)
			print(number)
      # activates when conditions are met 
		elif n <= 10 and n - int(n) == 0:
			number.insert(0,n)
			print(number)
			n=sum(number)
      #breaks the whole while loop 
      break (n) 
      #returns the value of n
	return (n)

#8

Don’t try random stuff because the initial thing “didn’t work”. Need to find the problem and fix that instead.

Exiting the function is something you do when you’re done, so you simply place that AFTER everything else. There should be no confusion around indentation here, because, again, you should do it after having finished computing, not during, not inside.

You’re still not using 4 spaces for indentation, and you’re still mixing tabs and spaces. Before doing anything else you should clean up your formatting, if it’s all a mess then it’ll only be harder to reason about.

while True:
    # indent by 4 when entering
    if True:
        # indent another 4 when entering body of if-statement
    # exit if-statement by de-indenting
# exit while-loop by de-indenting

# since the loop has been exited, and because this is on a line further down,
# this is *after* the loop

Obviously those comments should not exist in code, because the code itself says those things. Comments are not for stating the obvious.

Loops let you repeat something. So you indent the part to be repeated, add your for/while, and then to do something after the loop you put that below the loop, and not inside the loop, after, meaning you have to exit it first, which is done by de-indenting


#9

To multiply numbers 5 through 10, you’d have a loop counting through those numbers:

product = 1
for n in range(5, 11):
    product *= n

The loop counts, and each time you multiply.
Then you de-indent to exit the loop and place the code for presenting the result below:

product = 1
for n in range(5, 11):
    product *= n
print product

#10

Figure out your troubles with simpler code, and then come back to the bigger piece when you’re confident about how things fit together. Rewriting the same code may also help you, because then you’re adding things one at a time again, and you have to think about where each thing goes.

Don’t guess, try to back up everything you know with some reliable source, preferably official documentation. Everything needs to be argued for, reasoned about. “It should be this way because…

Take care of the formatting before doing anything else. It’s almost silly to consider anything else before fixing this, because it’s easy to fix and it makes everything else difficult.


#11

this what I got after using the indentation suggested but there is still an error you can see the contrast in the coding from the two screenshots.It still doesn’t return the value expected.



#12

The second one has no return statement so it will obviously not return anything
The first one uses t before it has been defined. You need to make sure that it gets defined for all numbers that are valid input, it’s not enough to work for some inputs


#13

I know that much. The second one was just to show that the actual function is doing everything that I want it to do except return t. how can I get it to return t . I tried indenting it outside the while loop but within the user-defined function but that didn’t work?


#14

Can’t return t if you haven’t defined t.
Not having defined t doesn’t mean that you should return it at a different time, it means that you didn’t ensure that it gets created in the first place

You have three conditions that have to be met in order to create t. That doesn’t happen for all valid inputs (and perhaps there shouldn’t be so much conditional code either)

And yet again, this isn’t a call to start shuffling your indentation around. Find the problem and fix that


#15

Popping off the last digit until there’s nothing left is one loop.
After that, return the result.

Note that there’s no need for an if-statement to do that.
There are things to do before and after the loop, but the thing that’s repeated is always the same, no condition. Pop off the last digit. Nothing else needs to be repeated.

Another thing that you shouldn’t be doing is converting to int. You should only ever have ints, so there’s nothing to convert from.

You also do not need to store digits, you only need to remember a sum.


#16

i realize there is an easier way to do it and i have coded an the easier way.
but for the purpose of understanding building my understanding i wanted to know what particular elements in my current code when taking this approach were wrong


#17

I’m not suggesting a different approach. But there are things that don’t need to happen.

Placing essential code behind several conditions, and when those conditions aren’t always met, then you’ll have cases where those essential parts simply don’t run. Fixing that involves fixing the conditions, but they’re not all doing something useful so fixing really means removing (because there’s nothing meaningful that you can put there)

If you have 1 + 1 + 1 - 1 - 3 + 1 + 1 then you’d start removing things that cancel each other out, until you’re left with only what you need. Though in your code they don’t just cancel out, they do things they shouldn’t at all.

You can’t fix something that has no purpose. There’s no correct configuration other than removing it. Yes, you can change something that is wrong into something that cancels out, but having code that does nothing isn’t helpful.


#18

Honestly, i cant see it. The print statements show that i am producing the value n which is being inserted on to the number array which is central to producing all my t. I am so confused as to where I am going wrong I have stripped the coded an written from scratch several times

def digit_sum(n):
    number =[]	
    while n>0: 
        if n %10 != 0 and n>10:
            number.insert(0,n%10)
            n = int((n - n%10)/10)
            print(number)      
        elif n <= 10: 
            number.insert(0,n)
            print(number)
            break
    t = sum(number)        
    return t

#19

see what?


#20

what is causing the t values not to be defined