in bellow python programm only else part of if condition executing

3051 views python
5

i am new to python coding and while running this code everything works fine except if condition

a = input("enter number 1")
b = input("enter number 2")

def sum(a,b):
    c = a + b   
    print(c)

sum(a,b)

if sum >= 100:
   print ("answer is more than 100")
else:
    print("answer is less than 100")

answered question

input returns a string. You need to convert it to an integer.

sum is a function, not a number. I would expect this to cause an error. You're also printing the result from the function instead of returning it, so you can't use the answer.

Not only that, but your function doesn't return anything, and you're not assigning the result to a global variable.

And finally, sum is a builtin so you should avoid using that name for your variables

2 Answers

6

In your code, sum isn't a variable you can check, it's a callable funciton. You need your sum function to return the value of the two numbers. As roganjosh put, input() gives you a string, so you need to convert that to a integer to add them together.

Try this:

a = input("enter number 1")
b = input("enter number 2")

# Instead of printing c, you're now returning c as the value from this function.
def my_sum(a,b):
    c = int(a) + int(b)
    return c 

print(my_sum(a,b))

if my_sum(a,b) >= 100:
   print ("answer is more than 100")
else:
   print("answer is less than 100")

posted this
9

The question results an error with sum is not defined..

posted this

Have an answer?

JD

Please login first before posting an answer.