1

Here's my code, Can you explain what's the mistake and am I not getting the proper output?

import sys

n = input()
m = input()

if (type(n) == type(int) and type(m) == type(int)):
    sum = n + m
    print(sum)
else:
    print("error")

I expect the output of 1 and 2 to be 3, but the actual output is error.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895

4 Answers4

0

input is returning a string. This code works:

try:
    n = int(input())
    m = int(input())
except ValueError:
    print('Please enter a number')

sum = n + m
print(sum)
Legorooj
  • 2,646
  • 2
  • 15
  • 35
0

Your approach doesn't work since input is always returning a string. Instead, you could use try and except to turn the string into an integer like this:

inp1 = input()
inp2 = input()

# try to change the type of the input into integer
try: 
    int_inp1 = int(inp1)
    int_inp2 = int(inp2)
    # if it works: print the sum of both integers
    sum1_2 = int_inp1 + int_inp2
    print(sum1_2)
# if it fails: print "error"
except:
    print("error")

See the documentation on handling exceptions.

trotta
  • 1,232
  • 1
  • 16
  • 23
0

Python Try Except:

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

try:
    n = int(input())
    m = int(input())
    sum = int(n) + int(m)
    print(sum)
except:
    print("error")

NOTE:

input() is returning string.

int(input()): if input string is representing an integer it will convert string into integer and try block will execute, othervise it will return an error and exept block will execute

ncica
  • 7,015
  • 1
  • 15
  • 37
-1

Your code is outputting error because type(int) returns type 'type', not integer. To correct this mistake you could simply:

import sys

n = input()
m = input()

if (type(n) == int and type(m) == int):
    sum = n + m
    print(sum)
else:
    print("error")

Although as other people are saying in their answers, it is generally more pythonic to use try except instead of if blocks. You can find further information about which is best in this question.

NOTE:

This answer is only valid for python 2

Lucas Wieloch
  • 818
  • 7
  • 19