【问题标题】:I get a value error when I change strings to integers [duplicate]将字符串更改为整数时出现值错误[重复]
【发布时间】:2021-04-25 00:32:49
【问题描述】:

每当我运行以下代码时,都会出现值错误。如何将以下代码从字符串更改为整数?谢谢

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)

【问题讨论】:

  • input('5') 不会像您认为的那样做。它不使用字符串'5',它只是使用5作为提示符
  • 我想可能是因为我将 str 输入转换为 int 它可以改变它。根据我正在学习的书。但非常感谢
  • v1 = input(5) v2 = input(3) total = int(v1) + int(v2) print ("the sum of", v1, "and", v2, "is? ",总计)
  • 我仍然有 vaule 错误

标签: python-3.x variables input integer


【解决方案1】:

您可能想要更改引号之间的提示。输入需要使用键盘输入,引号之间的短语是您在输入时会看到的提示。

这样,系统将提示您先输入变量v1,然后再输入变量v2。你应该确保你没有输入任何空格或字符串,只输入你想要求和的数字。或者,您还可以实现一个系统来检查用户输入是否为数字,否则,请用户再次输入数字。

选项 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 )

我希望它有助于解决您的疑问:)

【讨论】:

  • 不需要重复int(v1)!它可能更简单 - v1 =int(input(...)
  • 感谢您的建议!我只是想保持我的代码尽可能与原始代码相似,以便用户更好地理解它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 2011-09-03
  • 1970-01-01
相关资源
最近更新 更多