+ 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)
9 odpowiedzi
+ 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 ("+", "-", "*", "/"):
+ 8
a more advanced way of creating a calculator can be found here:
https://sololearn.com/compiler-playground/cleS33YqyE5Q/?ref=app
+ 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)
+ 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.
+ 1
Dvan Silva wrong thread? Only post on-topic replies, please. Kindly remove your reply.
+ 1
Dvan Silva
And don't post other people's code without a good reason.
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
0
..