The program accepts two input values, adds them and gives the amount to the user.

Before folding using the isdigit() function, isdigit() is checked that all the entered characters are numbers and numbers are separated using .split() to perform the increment operation of the result value. If the presence of extraneous characters is detected, an error message is displayed and the function is restarted.

If you enter numbers that contain more than one character, the numbers are not combined, as a result of which an error occurs (in the if-else )

I do not know how to solve the problem. It is advisable to do without separate input of each number and checking for it and WITHOUT using try-except , if possible. Thank you in advance.

Source:

 def sum(): num=input('enter two numbers with space') '''ввод двух исел через пробел''' result=0 '''присваивается результат суммы введенных чисел''' num = '0'.join(num) '''объединение введенных чисел через 0 ( ноль )''' if num.isdigit() == True: '''проверка на отсутствие символов кроме чисел''' '''разделение чисел по знаку 0''' num = num.split('0') '''увеличение result на значение введенных чисел''' for i in num: i=int(i) result+=i else: '''вывод сообщения об ошибке и запуск функции по новой''' print('you should enter only numbers') sum() '''вывод суммы''' print(result) '''начальный вызов функции''' sum() 
  • 100 + 1 = ['1', '', '', '1'] when connecting and split by zero. - floydya

1 answer 1

Via try + except:

 def summa(): num = input('enter 2 nums: ') try: return sum([int(i) for i in num.split()]) except TypeError: summa() print(summa()) 

Without:

 array = [] while len(array) < 2: a = input() if a.isdigit(): array.append(int(a)) print(sum(array)) 
  • Forgot to write, you can not use try-except - Vy Qwe
  • one
    @VyQwe set this condition to you poorly knows Python. - Sergey Gornostaev
  • @SergeyGornostaev, most likely I just misunderstood the task and it did not mean that you need to enter numbers in a single input function. - Vy Qwe
  • @VyQwe added option without try + except - floydya