当我将字符串更改为整数时出现值错误
I get a value error when I change strings to integers
每当我 运行 以下代码时,我都会收到一个值错误。如何将以下代码从字符串更改为整数?谢谢
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)
或选项 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)
您可能想要更改引号之间的提示。输入需要用键盘输入,引号之间的短语是输入时看到的提示。
这样,系统将提示您先输入变量 v1
,然后再输入变量 v2
。你应该确保你没有输入任何 space 或字符串,只是你想要求和的数字。或者,您也可以实现一个系统来检查用户输入的是一个数字,否则要求用户再次输入该数字。
选项 1 将是:
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 )
选项 2(检查用户是否输入了数字):
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 )
希望对您的疑惑有所帮助:)
每当我 运行 以下代码时,我都会收到一个值错误。如何将以下代码从字符串更改为整数?谢谢
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)
或选项 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)
您可能想要更改引号之间的提示。输入需要用键盘输入,引号之间的短语是输入时看到的提示。
这样,系统将提示您先输入变量 v1
,然后再输入变量 v2
。你应该确保你没有输入任何 space 或字符串,只是你想要求和的数字。或者,您也可以实现一个系统来检查用户输入的是一个数字,否则要求用户再次输入该数字。
选项 1 将是:
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 )
选项 2(检查用户是否输入了数字):
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 )
希望对您的疑惑有所帮助:)