How to do this... my first approach was to make the values a list and then use the sum() function. Guess im too noob for that. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to do this... my first approach was to make the values a list and then use the sum() function. Guess im too noob for that.

Lesson 26.3 in python core. Cant seem to find a way. Any advise is appreciated

27th Aug 2021, 5:40 PM
nabeer zahed chowdhury
nabeer zahed chowdhury - avatar
2 Answers
+ 5
nabeer zahed chowdhury , are talking about to sum the digits of a number? as there are various approaches, it would be good if you can show us your attempt until now. thanks! to give you a hint (using string): ▪︎use the string input of the number ▪︎create a variable 'total' that will hold the running sum of the digits ▪︎when using a for loop you will get one digit per each cycle of the loop in a loop variable ▪︎convert the value from the loop variable to int and add it to 'total' ▪︎ when the loop is finished you have the sum in 'total' and can print it happy coding and good success!
27th Aug 2021, 6:48 PM
Lothar
Lothar - avatar
+ 1
The exercise you refer is about a simple while loop. Observe how the initial program works. In every iteration, it increments the length by 1. So after all digits are consumed, the length contains the number of digits. What you need to do instead, is add the last digit to the total, rather than 1. You get the last digit with n%10
27th Aug 2021, 6:45 PM
Tibor Santa
Tibor Santa - avatar