【问题标题】:Checking if a variable is a number in Python [duplicate]检查变量是否是Python中的数字[重复]
【发布时间】:2021-02-09 23:55:42
【问题描述】:

我正在构建一个预算工具。如果用户输入了错误的预算数字,整个程序就会崩溃并给出错误消息。我想添加一个循环或其他东西让程序循环回来并再次提出问题,而不是在给出无形信息时崩溃。我试过while循环,但它似乎不起作用


while answer != "yes" or answer == "Yes" or answer == "YES":
   print("Hmmm, okay. Try again.")
   answer = input("Ready to budget your travel expenses? ")

budget = int(input("What's your budget? $")**

【问题讨论】:

  • 它给出的错误信息是什么?
  • 错误消息:回溯(最近一次调用最后一次):文件“main.py”,第 70 行,在 预算 = int(input("What's your budget?$")) ValueError:基数为 10 的 int() 的无效文字:'gh'
  • 你在while条件下的比较不一致,连词错误。

标签: python python-3.x


【解决方案1】:

将输入改为while True 循环,并在获得所需输入后使用break。这是一个简单的例子:

while True:
     answer = input("Ready to budget your travel expenses? ")
     if answer.lower() == "yes":
         break
     print("Hmmm, okay.  Try again.")

while True:
    try:
        budget = int(input("What's your budget? $"))
        break
    except ValueError:
        print("Nope, that's not a number.")

【讨论】:

  • 代码的开头部分可以正常工作。但是,当预算代码设置为“int”时,如果用户输入字母而不是数字,程序会崩溃
  • 你想让它做什么?
  • 问题出在预算变量上
  • 当提示用户输入预算数字时,如果他们输入字母..程序崩溃。相反,我需要让它询问直到给出一个数字
  • 只需使用与获得“是”相同的技术。我会更新答案,希望连续看到两个示例会有所帮助。 :)
猜你喜欢
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 2018-10-06
  • 2014-10-03
  • 1970-01-01
  • 2015-03-17
  • 2012-09-21
相关资源
最近更新 更多