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

问题描述 投票:-1回答:2
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”时,我试图使python代码自行关闭。当我尝试这样做时,python向我发送一条错误消息:

TypeError: float() argument must be a string or a number, not 'NoneType'

有帮助吗?

python
2个回答
3
投票

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

if first=="x" and second=="x":

但是您已经将None修改为它们,所以它们不再是x,应该是以下内容

if first is None and second is None:

您有两个选择

  1. 如果未给出仅默认值,则提供默认值

    if first == "x" and second == "x":
        print("You have not used any numbers. Disabling calculator...")
        sys.exit()
    elif first == "x":
        first = 0
    elif second == "x":
        second = 0
    
    first = float(first)
    second = float(second)
    
  2. 即使只有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)
    

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

any(map(str.isnumeric, [first, first.strip("-+")]))
  • 测试值本身或没有符号的值
  • 仅是数字:仅数字和点
  • [any以获取它的值或不带符号的值

-5
投票

更改:如果第一和第二==“ x”:

至:如果第一和第二== None:

© www.soinside.com 2019 - 2024. All rights reserved.