-1

Anytime I run the following code I get a value error. How can I change the following code from string to integers? Thanks

v1 = "5"
v2 = "3"

#covert to int 
v1 = int(v1)
v2 = int(v2)

#save the sum of v1 and v2 into to var total
total = v1 + v2

print("The sum of :", v1 , "and", v2, "is", total)

Or option 2

v1 = input("Please enter a number: ")
v1 = int(v1) 
v2 = input("Please enter a number: ")
v2 = int(v2)

#save the sum of v1 and v2 into to var total
total = v1 + v2

print("The sum of :", v1 , "and", v2, "is", total)
Thesonter
  • 182
  • 12

1 Answers1

1

You might want to change the hints in between the quotes. The input needs to be entered with the keyboard, and the phrase in between the quotes is the hint that you will see while entering the input.

This way, you will be prompted for entering an input for the variable v1 first and then for the variable v2. You should make sure you do not enter any space or string, just the number you want to sum. Alternatively, you can also implement a system that checks that the user input is a number or, otherwise, asks the user to introduce the number again.

The option 1 would be:


v1 = input ('Please Introduce the first number')

v1 = int(v1)

v2 = input('Please introduce the second number')

v2 = int(v2)

total = int(v1) + int(v2)

print ("the sum of", v1, "and", v2, "is?", total )

Option 2 (checking that the user entered a number):


correctNumbers = False

while (not correctNumbers):

    try:
        v1 = input ('Please introduce the first number')
        v2 = input ('Please introduce the second number')
        v1 = int(v1)
        v2 = int(v2)
        correctNumbers=True
    except:
        print ("At least one of the two numbers contained a wrong character, please try again.")

total = int(v1) + int(v2)

print ("the sum of", v1, "and", v2, "is?", total )

I hoped it helped to solve your doubt :)

rodvictor
  • 323
  • 1
  • 10
  • 1
    There is no need to do `int(v1)` repeatedly! It could be simpler just - `v1 =int(input(...)` – Daniel Hao Jan 20 '21 at 16:36
  • 1
    Thanks for the suggestion! I was just trying to maintain my code as similar as possible to the original one so the user could understand it better :) – rodvictor Jan 20 '21 at 16:38