Python - sum of two numbers program error

后端 未结 3 1206
萌比男神i
萌比男神i 2021-01-21 17:26

I was just getting into Python programming. I wrote a simple program to calculate sum of two user-input numbers:

a,b = input(\"enter first number\"), input(\"ent         


        
相关标签:
3条回答
  • 2021-01-21 17:54

    input() in Python 3 returns a string; you need to convert the input values to integers with int() before you can add them:

    a,b = int(input("enter first number")), int(input("enter second number"))
    

    (You may want to wrap this in a try:/except ValueError: for nicer response when the user doesn't enter an integer.

    0 讨论(0)
  • 2021-01-21 17:55

    instead of (a+b), use (int(a) + int(b))

    0 讨论(0)
  • 2021-01-21 17:56

    I think it will be better if you use a try/except block, since you're trying to convert strings to integers

    try:
        a,b = int(input("enter first number")), int(input("enter second number"))
        print("sum of given numbers is ", (a+b))
    except ValueError as err:
        print("You did not enter numbers")
    
    0 讨论(0)
提交回复
热议问题