mardi 9 mars 2021

Python: If/elif/else Statement Not Working as Expected?

So I have the user input an expression:

Example:

1 + 1
d * 3
100 / j
s * c

To allow the user to mix numbers (int) and letters (str) I have the following if statement:

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")

Dictionary Code

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

If I type (well testing it): 1 + 1 it will execute the else statement (as it should). However, if you type any of the other combinations:

a + a
1 + a
a + 1

It ignores the if and elif statements and tries to executes else & failes.

So I type

23 * 23

Output:

4th

I type

a + 1 or a + a or 1 * a

Output is:

ValueError: invalid literal for int() with base 10:

So my if statement is failing and being new to (programming in general) I was wondering if there is a better way to do what I'm trying to do above. Maybe something I've over looked or under looked?

Would a for be better suited or would it give me the same error?

Feel free to link me to any thing you think could be helpful in helping me get this working.

Aucun commentaire:

Enregistrer un commentaire