【发布时间】:2021-06-07 21:54:54
【问题描述】:
所以我让用户输入一个表达式:
示例:
1 + 1
d * 3
100 / j
s * c
为了允许用户混合数字 (int) 和字母 (str),我有以下 if 语句:
user_input = input("Enter a math Equation: ")
user_input = user_input.strip().split(" ")
user_c1 = user_input[0]
user_c2 = user_input[2]
user_c3 = user_input[1]
l1 = user_c1
l2 = user_c2
l3 = user_c2
l6 = user_c1
l4 = int(user_c2)
l5 = int(user_c1)
l7 = int(user_c1)
l8 = int(user_c2)
if l1 and l2 in kb_dxnry:
print("1st")
elif l3 in kb_dxnry and l4 not in kb_dxnry:
print("2nd")
elif l5 not in kb_dxnry and l6 in kb_dxnry:
print("3rd")
else:
print("4th")
字典代码
user_kb_dxnry = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6,
'g': 7, 'h': 8, 'i': 9, 'j': 10, "k": 11, "l": 12,
"m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18,
"s": 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24,
'y': 25, 'z': 26, "0": 0
}
kb_dxnry = user_kb_dxnry
如果我输入(很好地测试它): 1 + 1 它将执行 else 语句(应该如此)。但是,如果您键入任何其他组合:
a + a
1 + a
a + 1
它忽略 if 和 elif 语句并尝试执行 else & 失败。
所以我输入
23 * 23
输出:
第四个
我输入
a + 1 or a + a or 1 * a
输出是:
ValueError: invalid literal for int() with base 10:
所以我的 if 语句失败并且是新手(一般编程)我想知道是否有更好的方法来做我在上面尝试做的事情。也许是我看多或少看的东西?
a 会更适合还是会给我同样的错误?
请随时将我链接到您认为有助于我完成这项工作的任何内容。
编辑:
或许这样会更好:
user_input = input("Enter a math Equation: ")
user_input = user_input.strip().split(" ")
user_c1 = user_input[0]
user_c2 = user_input[2]
user_c3 = user_input[1]
l1 = user_c1
l2 = user_c2
l3 = user_c2
l6 = user_c1
user_input = input("Enter a math Equation: ")
user_input = user_input.strip().split(" ")
user_c1 = user_input[0]
user_c2 = user_input[2]
user_c3 = user_input[1]
l1 = user_c1
l2 = user_c2
l3 = user_c2
l6 = user_c1
l4 = user_c2
l5 = user_c1
l7 = user_c1
l8 = user_c2
if l1 in kb_dxnry and l2 in kb_dxnry:
print("1st")
elif l3 in kb_dxnry and l4 not in kb_dxnry:
l4 = int(user_c2)
print("2nd")
elif l5 not in kb_dxnry and l6 in kb_dxnry:
l5 = int(user_c1)
print("3rd")
else:
l7 = int(user_c1)
l8 = int(user_c2)
print("4th")
好吧,重写上面的代码,ErrorValue 已经消失了。但如果你输入 a + 1 或 1 + a
它仍然跳过 elif 1 和 2:
elif l3 in kb_dxnry and l4 not in kb_dxnry:
print("2nd")
elif l6 in kb_dxnry and l5 not in kb_dxnry:
print("3rd")
然后跳转到其他地方。
【问题讨论】:
-
if l1 and l2 in kb_dxnry:应该是if l1 in kb_dxnry and l2 in kb_dxnry:
标签: python python-3.x dictionary if-statement valueerror