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?
7 Respostas
+ 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)
+ 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)
0
Thanx guys.. Will someone please give exact example using any number?
0
Show us what you've tried so far and explain why you are stuck.
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.
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]))
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.