[英]This Python script returns “KeyError: '6'” and I don't know why
[英]I made a really basic script using Python (I am new at it) and i don't know why it is not working as it should work
问题出在第 19 行,即if
条件所在的位置。
因此,当您运行代码时,它应该要求您输入第一个数字,然后是数学运算(+、加号或 -、减号),最后是第二个数字。
当您添加(加号)时它工作得很好,但是当您尝试减去时它会显示消息“无效操作”,我已经尝试使用其他逻辑运算符但它不起作用 D:
请解释一下有什么问题,因为我看不到它。
minus = ["-","minus"]
plus = ["+", "plus"]
print("""
===========================
CALCULATOR
===========================
1 2 3 +
4 5 6 -
7 8 9
0 Total:
===========================
===========================
""")
n1 = int(input("First Number: "))
operation = input("+ or - ")
if operation not in (minus,plus):
print("Invalid Operation")
else:
n2 = int(input("Second Number: "))
if operation in minus:
total_minus = n1-n2
print(f"""
===========================
CALCULATOR
===========================
1 2 3 +
4 5 6 -
7 8 9
0 Total: {total_minus}
===========================
===========================
""")
elif operation in plus:
total_plus = n1 + n2
print(f"""
===========================
CALCULATOR
===========================
1 2 3 +
4 5 6 -
7 8 9
0 Total: {total_plus}
===========================
===========================
""")
表达式operation not in (minus,plus)
正在测试是否operation
是元组(minus, plus)
中的minus
或plus
列表之一。 由于它是一个字符串,它永远不会是这些值中的任何一个。
我建议创建一个有效操作的组合列表。
valid_operations = minus + plus # concatenate valid operations
然后测试以查看用户输入的操作是否在该列表中。
if operation not in valid_operations:
print("Invalid Operation")
else:
...
这样很容易将您的计算器扩展到乘法、除法等。
您正在通过形成一个元组来加入列表:
if operation not in (minus, plus):
您真正想要做的是将列表添加在一起:
if operation not in minus + plus:
operation not in (minus,plus)
将始终为真。 operation
是一个字符串, (minus,plus)
是一个包含两个列表的元组。
如果您想测试字符串operation
是在minus
列表还是plus
列表中,您可以改用:
if operation not in (minus + plus):
对我来说,您的代码不适用于 + 或 -! 我不知道为什么它对你有用 + 因为我认为它不应该!
你是正确的,问题是你的 if 语句。 当你写:
if operation not in (minus,plus):
您是在说“如果运算不等于 ["-", "minus"] 或 ["+", "plus"]"
换句话说,您正在将用户的输入与 2 个字符串的列表进行比较!
你可以改为写:
if operation not in minus and operation not in plus:
你的程序就可以正常工作了
只需更改 if 代码块
if operation in plus or operation in minus:
your code
else:
print("Invalid Operation")
你写了:
if operation not in (minus,plus):
your code
这将始终为 True,因为operation
永远不会在两个列表(加号和减号)中,因此该语句为 False,并且由于您写了 'not in',不是 False 为 True,这就是您总是得到“无效操作”的原因在你的 if 块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.