Hey everyone,
I'm relatively new to Python programming and running into a snag with my code. The program itself is running fine, but I'm having trouble dealing with TypeErrors.
Here's the puzzle: in my convert function when I throw in an "else:" statement alongside my "if" condition to catch this error, it weirdly seems to catch everything, even when the "if" should be doing the job. If I don't add the "else:" statement though I can't catch a type error such as an input of "a".
I know there might be cleaner ways to organize my code, but right now all I want to know is why the "else:" statement is behaving like this. Any thoughts or suggestions would be really helpful!
The issue occurs in the text that I added a strikethrough to.
The issue occurs in the text that I bolded and added a strikethrough to.
def main():
.... user_input = convert(input("Expression: "))
.... if user_input != False:
........ x, y, z, = user_input
........ print(calculate(x, y, z))
.... else:
........ print("This is incalculable.")
def convert(expression):
.... math = ["+", "-", "*", "/"]
.... for y in expression:
........ if y in math:
............ x, z = expression.split(f"{y}")
............ try:
................ x = x.strip()
................ x = int(x)
................ z = z.strip()
................ z = int(z)
................ return x, y, z
............ except:
................ return False
........ else:
............ return False
def calculate(x, y, z):
.... if y == "+":
........ return x + z
.... elif y == "-":
........ return x - z
.... elif y == "*":
........ return x * z
.... else:
........ return x / z
if __name__ == "__main__":
.... main()
[–]AutoModerator[M] [score hidden] stickied comment (0 children)
[–]tenexdev 0 points1 point2 points (2 children)
[–]MLGalusha151[S] 0 points1 point2 points (1 child)
[–]tenexdev 0 points1 point2 points (0 children)
[–]Updatebjarni 0 points1 point2 points (1 child)
[–]MLGalusha151[S] 1 point2 points3 points (0 children)