0

How to split up user's input? For example, user gave an input 27, I want to split 2 and 7 and add them to get answer as 9. How could I write program for this?

26th Sep 2016, 2:03 AM
Vishal Lagoo
Vishal Lagoo - avatar
7 ответов
+ 1
If you havent already converted the input to an integer, you can access each character by its index number, like you would with a list. Convert those digits to integers so you can add them. e.g. num = input() sum = 0 for i in num: sum = sum + int(i) print(sum)
26th Sep 2016, 12:52 PM
Gershon Fosu
Gershon Fosu - avatar
+ 1
If you turn 27 into the string num="27", you can access the digits of 27 by indexing: num[0] is "2" and num[1] is "7". Note that "2" and "7" are strings, so you have to convert them to integers before summing them up. For a more general solution, try a for loop, e.g., num = "2742" sum = 0 for digit in num: sum += int(digit)
27th Sep 2016, 9:35 PM
jeroen
0
Thanx guys.. Will someone please give exact example using any number?
29th Sep 2016, 2:03 PM
Vishal Lagoo
Vishal Lagoo - avatar
0
Show us what you've tried so far and explain why you are stuck.
29th Sep 2016, 2:06 PM
jeroen
0
Actually I didnt understood in terms of your answers. Thanking you for answers, but I think it will be more clear if you will givee example.
29th Sep 2016, 2:24 PM
Vishal Lagoo
Vishal Lagoo - avatar
0
Vishal, try the following commands and experiment with them. Do you see that python treats integers and strings differently? You can split strings, but you cannot add them. You can add ints, but you can't split them. num = 27 type(num) str(num) type(str(num)) numstr = "27" #alternatively, try numstr = str(num) type(numstr) numstr[0] numstr[1] type(numstr[0]) int(numstr[0]) int(numstr[1]) type(int(numstr[0]))
29th Sep 2016, 7:00 PM
jeroen
0
print("Please, enter your birthday:") birthday =input() sum = 0 for digit in birthday: sum += int(digit) print("Your number in numerology is %s ." %s (sum) that will output the sum of the number`s digits given by the user.
21st Nov 2016, 5:44 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar