Home > Back-end >  How To Separate Index from userInput and add( ) them as INT in While Loop?
How To Separate Index from userInput and add( ) them as INT in While Loop?

Time:09-27

somebody says me to solve this.

condition is:

input any number from user (it can be 4 digit or five or whatever) e.g. '1234' it will be in string what i have to do just separate those number and do addition of those indexes as int

-------------------i have done this----------------------------------------------

usrInput = input("Type a number you want to some: ")

len = len(usrInput)

n = 0

i = 1

while i<=len:
    index = int(usrInput[n]) #1
    n =1
    i =1

now if i print(index) it will separate those numbers in separted index

now how can i do addition of them in this while loop i need help!!!!!!!!!

enter image description here

CodePudding user response:

There are a few different ways you can individually access the values from the string. Going with your approach, if you want to get the sum of all the numbers, all you have to do is initialize a variable to 0 and add the numbers as you iterate through them in the loop.
In your program you had used two variables i and n to basically perform the same task. You don't need two separate variables to access the value from the string and increment the loop.

usrInput = input("Type a number you want to add: ")
sumval = 0
i = 0

while i< len(usrInput):
    index = int(usrInput[i]) #1
    sumval =index
    i =1

print(sumval)
  • Related