简体   繁体   中英

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))

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

char分配了值(0, 1, ..., len(S)-1) ,因此chr(char)永远不会等于'+'

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))

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM