How do I combine functions in python?

Viewed 65

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.

1 Answers

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