![](/img/trans.png)
[英]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.