My input runs when not supposed to [duplicate]

2020-05-01 17:24发布

问题:

my problem here is that I'm trying to make a better, more compressed but still advanced calculator with text outputs and everything. It's still in a very, VERY early stage as I came across a problem.

#!/usr/bin/python
import math
import time
import random
op=input('add/sub/mul/div/sqrt/n!/pow/ctof/hex')
if op==('ctof'):
    choice=input('C to F or F to C. 1 or 2')
    if choice=='1':
        c=float(input('Input Celcius'))
        print(str(c)+' Degrees Celcius = '+str(c*1.8+32)+' Degrees Fahrenheit')
    if choice=='2':
        f=float(input('Input Fahrenheit'))
        print(str(f)+' Degrees Fahrenheit = '+str((f-32)/1.8)+' Degrees Celcius')
    else:
        print('Invalid operation')
if op==('sqrt')or('n!'):
    x=float(input('Input X'))
    if op==('sqrt'):
        print('The square root of '+str(x)+' is: '+str(math.sqrt(x)))
    if op==('n!'):
        print('The factorial of '+str(x)+' is: '+str(math.factorial(x)))
else:
    x=float(input('Input X'))
    y=float(input('Input Y'))
if op==('add'):
    print(str(x)+' + '+str(y)+' = '+str(x+y))

The thing is that the x inputin the square root and factorial condition runs instead of the else: one. So when I use add it says that Y is missing. What am I doing wrong and why does the wrong input start.

By the way, sorry for the messy code. As said I wanted it to be compact. Plus I think It's a beuty to look at personally(if it was working).

回答1:

The comparison you want is the following:

if op == 'sqrt' or op == 'n!':

The issue with your code:

if op == 'sqrt' or 'n!':

is that it always evaluates to true because 'n!' is a constant truthy value. It does not evaluate what you think it evaluates, it does something like this:

if (op == 'sqrt') or 'n!':

which becomes

if (op == 'sqrt') or True: