+ 1

# Anyone see what's wrong with this code?(Python)

After making a complete calculator, I wanted to see if I could shorten the code to something like this: num1 = float(input()) op = input() num2 = float(input() if op == "+" or "-" or "*" or "/": print(num1 + op + num2) (I won't edit this code for the sake of being consistent with the replies, thank you all)

5th Dec 2023, 2:52 AM
Aza
9 Respostas
+ 6
Aza the conditional expressions between logical or operators do not compare anything. To illustrate how to make it work, here is an example: if op=="+" or op== "-" or op=="*" or op=="/": If you don't enjoy typing, then you could do this: if op in ("+", "-", "*", "/"):
5th Dec 2023, 3:22 AM
Brian
+ 8
a more advanced way of creating a calculator can be found here: https://sololearn.com/compiler-playground/cleS33YqyE5Q/?ref=app
5th Dec 2023, 10:59 AM
Lothar
+ 5
Aza , the required mathematical operation can *not* be done like: if op == "+" or "-" or "*" or "/": print(num1 + op + num2) (don't use the above code) > if we really want to calculate in a basically way it can to be done like: if op == '+': res = num1 + num2 elif op == '-': res = num1 - num2 elif op == '*': res = num1 * num2 elif op == '/': res = num1 / num2 print(res) (each operator has to be checked individually)
5th Dec 2023, 7:23 AM
Lothar
+ 4
There are few errors in your code. Line 3 is missing a closing bracket. Line 4 the condition is wrongly written. It should be if op == '+' or op == '-' or op == '*' or op == '/': Or simply If op in '+-*/' But most importantly, line 5 will throw an "unsupported operand type(s) for +: 'float' and 'str'" error. You cannot concatenate int and str, so 'float' in line 1 and line 3 is not necessary.
5th Dec 2023, 3:24 AM
Wong Hei Ming
+ 1
7th Dec 2023, 8:25 AM
Brian
+ 1
Dvan Silva And don't post other people's code without a good reason.
7th Dec 2023, 11:27 AM
Wong Hei Ming
0
Hey u can use of if else statement And also remove this op and use option=input("enter from these +/-/*/Ć·") then give seperate if elif to all of the operations
6th Dec 2023, 10:31 AM
Hritik Sharma
0
..
6th Dec 2023, 8:00 PM
ŠŠ»Š°Š“ ŠŠ°Š·Š°ŠŗŠ¾Š²
6th Dec 2023, 8:55 PM
Dvan Silva