如何在python中为一个简单的计算器修复此命令

如何在python中为一个简单的计算器修复此命令,python,Python,这是我在计算器中代码的一部分,但它不喜欢按我希望的方式运行 我试图让python代码在用户在两个变量处输入x时自动关闭。当我尝试执行此操作时,python会向我发送一个错误,说明: first = input("What is your first number?(type x to do nothing) ") second = input("What is your second number?(type x to do nothing) ") if first == "x": f

这是我在计算器中代码的一部分,但它不喜欢按我希望的方式运行

我试图让python代码在用户在两个变量处输入x时自动关闭。当我尝试执行此操作时,python会向我发送一个错误,说明:

first = input("What is your first number?(type x to do nothing) ")
second = input("What is your second number?(type x to do nothing) ")

if first == "x":
    first = None

if second == "x":
    second = None

if first and second == "x":
    print("You have not used any numbers. Disabling calculator...")
    sys.exit()

first = float(first)
second = float(second)
有什么帮助吗?

更改: 如果第一个和第二个==x:

致:
如果first和second==None:

要检查两个变量是否等于某个值,必须运行两个测试

TypeError: float() argument must be a string or a number, not 'NoneType'
但是,由于您已将“无”修改为“无”,因此它们不能再是x,应该是以下内容

if first=="x" and second=="x":
你有两个选择

如果只给出一个默认值,则给出一个默认值

if first is None and second is None:
即使2中只有一个是x,也要停止程序

因为这不是问题,而是一个很好的建议,可以帮助您:验证该值是否为数字

if first == "x" or second == "x":
    print("You have not used any numbers. Disabling calculator...")
    sys.exit()

first = float(first)
second = float(second)
测试值本身或不带符号的值 只是数字:只有数字和点 任何值都可以获取该值或不带符号的值
当他们输入“x”时,你输入=None,然后试图将None转换为float。另外,如果first和second==x没有做你认为它做的事情,这两个都是错误的,并且没有解决错误的根源。请查看我上面的评论。If应该是如果1==没有,第二=NoEI也会考虑改变验证,只需检查字符串是否是整数。这将允许您输入正数和负数:anymapstr.isnumeric,[first,first.strip-+]
if first == "x" or second == "x":
    print("You have not used any numbers. Disabling calculator...")
    sys.exit()

first = float(first)
second = float(second)
any(map(str.isnumeric, [first, first.strip("-+")]))