Skip to main content
 首页 » 编程设计

python之即使条件尚未满足,程序也会停止

2024年09月07日8www_RR

即使我有它,当我按 Y 或 N 时它会打印“that wasn't an option”

我把它设置为 !=(不等于)

if c.upper() != 'N' or "Y":  
    print ("that wasn't an option") 
if c.upper() != 'N' or "Y":  
    sys.exit() 

完整代码

import sys 
c = input('do you like piza? Y or N:') 
if c.upper() != 'N' or "Y": print ("that wasn't an option") 
if c.upper() != 'N' or "Y": sys.exit() 
if c.upper() == 'Y': 
print ('Me To')  
if c.upper() == 'N': print ("really i thought everybody likes piza.") 
if c.upper() == 'N': sys.exit() 
name = input("sooo what's ur name? ") 
print("that a pretty good name i guess ")` 

请您参考如下方法:

您犯了一个错误,就是在没有指定条件的情况下只放置了 or 语句。您必须指定另一个条件,而不仅仅是 或 值。在这里,我提供了一个示例。

import sys 
c = input('do you like piza? Y or N:') 
if c.upper() != 'N' or c.upper() != "Y":  
    print ("that wasn't an option") 
if c.upper() != 'N' or c.upper() != "Y":  
    sys.exit() 
if c.upper() == 'Y': 
    print ('Me To')  
if c.upper() == 'N':  
    print ("really i thought everybody likes piza.") 
if c.upper() == 'N':  
    sys.exit() 
name = input("sooo what's ur name? ") 
print("that a pretty good name i guess ") 

您还可以通过组合最后 2 个 if 来稍微重构代码,如下所示:

if c.upper() == 'N': 
    print("really i thought everybody likes piza.") 
    sys.exit() 

还有前两个 if 是这样的:

if c.upper() != 'N' or c.upper() != "Y":  
    print ("that wasn't an option") 
    sys.ext() 

编辑

or 应替换为 and,否则该检查没有意义。

感谢 khelwood 指出这一点。

希望这对您有所帮助!