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'
有帮助吗?
要检查两个变量是否等于某个值,必须运行两个测试
if first=="x" and second=="x":
但是您已经将None
修改为它们,所以它们不再是x
,应该是以下内容
if first is None and second is None:
您有两个选择
如果未给出仅默认值,则提供默认值
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个是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
以获取它的值或不带符号的值更改:如果第一和第二==“ x”:
至:如果第一和第二== None: