user3384468
user3384468

Reputation: 9

For loops python (beginner): Don't know why this won't work

So I'm trying to create a program that takes an input such as "34123+74321" and outputs the answer using a for loop. I'm stuck and don't know why my following code won't work:

S = str(input())
for char in range(0, len(S)):
    x = S[1:char]
    p = int(char)+1 
    z = S[p:]
    if chr(char) == "+":
        print (int(z)+int(x))

Upvotes: 0

Views: 102

Answers (4)

ssm
ssm

Reputation: 5383

You are using a loop to find the position of the '+' character right? Then the code should read:

for char in range(len(S)): 
    if S[char] == '+': pos = char

Then you can go ahead and take the lengths:

z = S[pos+1:]
x = S[:pos]
print int(x) + int(z)

However, note that this is not a very pythonic way of doing things. In Python, there is a string method index which already finds the position you are looking for:

pos = '1234+5678'.index('+') 

An easier way (and more Pythonic) of doing this would be:

x, z = '1234+5678'.split('+')

Of course, you could also do:

print sum(map(int, S.split('+')))

Which would also work if you have a number of items to add.

If you are starting to learn Python, it would be better if you understand that everything is an object and has its own methods. The more you learn about the methods, the better you will be at Python. It is a higher level program than your traditional languages, so try not to be limited by the same algorithmic structures which you are used to.

Cheers, and happy programming!

Upvotes: 0

anon582847382
anon582847382

Reputation: 20391

It would be much easier to do something like this:

>>> s = input()
34123+74321
>>> print(sum(int(x) for x in s.split('+')))
108444

Broken down:

  1. Makes a list of number-strings, by splitting the string into parts with '+' as the delimiter.

  2. for each value in that list, converts it to an integer.

  3. Find the total or sum of those integers.

  4. print out that value to the screen for the user to see.

You could also try:

>>> import ast
>>> s = input()
34123+74321
>>> ast.literal_eval(s)
108444

Upvotes: 4

Chrisji
Chrisji

Reputation: 311

char gets assigned the values (0, 1, ..., len(S)-1) and therefore chr(char) will never be equal to '+'.

Upvotes: 2

glglgl
glglgl

Reputation: 91139

Probably you mean if s[char] == "+":.

In general, you should try to use "speaking" variable names.

E. g., instead of char, it would better to use idx or something.

string = str(input())
for idx in range(0, len(string)):
    if string[idx] == "+":
        part1 = string[1:idx]
        part2 = string[idx+1:]
        print (int(part1) + int(part2))

Upvotes: 0

Related Questions