0

I am writing a python code that should convert str to int and find the sum of the inputs. Here's the code:

def convert_add():
    strings=[]
    n=int(input('Enter the list size: '))
    for i in range(0,n):
        print('Enter a string:',i)
        item=(input())
        if item==str:
            strings.append(len(item))
            print(sum(strings))
        else:
            strings.append(int(item))
            print(sum(strings))
convert_add()

So here's the thing, when I run this code it sums up the length of the strings I input, but I also want it to sum up integers. Since its a len function inputting a number(int) does the same thing it does to a string, it counts the figures, but I want an output of lets say 10 and 20 to be 30 and not 4. I have tried using the if statement and it's not working, i.e if item==str use the len fn else it sums. I am still a beginner and would love to know if there is a way I can combine them. Thanks.

4
  • 2
    You are telling it to append the length of the string. Instead, append the string as a number: strings.append(len(item)) --> strings.append(int(item)) Commented Sep 13, 2022 at 19:50
  • I have tweaked the code a little bit by including the if statements that I was using to try and make the idea I have in my head work. However, only one of the statements is working. Is there a way it can be both, is the 'if item==str' wrong? Commented Sep 13, 2022 at 20:22
  • In this case, item will never be equal to str, as str is a builtin type. What are you trying to accomplish here? The return type from the input function is always of type str. Do a bit of research in detecting if a string contains only digits, or alpha characters. (I believe that’s what you’re trying to accomplish here(?)) Commented Sep 13, 2022 at 20:29
  • I am trying to get an output from the sum of length of strings that I append or the sum of integers that I append. I'll do a little more digging. Thanks :-) Commented Sep 13, 2022 at 20:43

1 Answer 1

1

You can combine.
Note that for input combined at the same time, for example 'str' and 10,
you will get an aggregate value of 13.

def convert_add():
    strings = []
    n = int(input('Enter the list size: '))
    for i in range(n):
        item = input(f'Enter a string {i + 1}: ')
        try:
            strings.append(int(item))
        except ValueError:
            # That's not an int
            strings.append(len(item))
        print(sum(strings))

convert_add()
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, this is even better than I'd hoped. Thanks alot :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.