Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中检查变量是否为数字_Python_Python 3.x - Fatal编程技术网

在Python中检查变量是否为数字

在Python中检查变量是否为数字,python,python-3.x,Python,Python 3.x,我正在建立一个预算工具。如果用户为预算输入了错误的数字,整个程序就会崩溃并发出错误消息。我想添加一个循环或其他东西,让程序返回并再次提出问题,而不是在给定无形信息时崩溃。我试了一会儿,但似乎不起作用 while answer != "yes" or answer == "Yes" or answer == "YES": print("Hmmm, okay. Try again.") answer = i

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


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? $")**

将输入改为
while True
循环,并在获得要查找的输入后
中断。下面是一个简单的例子:

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.")

它给出的错误消息是什么?错误消息:回溯(最近一次调用last):文件“main.py”,第70行,在budget=int(输入(“您的预算是多少?”))值错误:int()的文本无效,以10为基数:'gh'当
条件不一致时,您在
中的比较,连接词是错误的。代码的开头部分工作正常。但是,当预算代码设置为“int”时,如果用户输入字母而不是数字,程序将崩溃。您希望它做什么?问题在于预算变量。当提示用户输入预算数字时,如果用户输入字母。。程序崩溃了。相反,我需要让它询问,直到给出的数字必须使用与获得“是”相同的技巧。我将更新答案,希望连续看到两个示例会有所帮助。:)