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

时间:2018-04-24 13:30:09

标签: python python-3.x

打印“那不是一个选项”当我按Y或N时,即使我有它

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

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 ")`

1 个答案:

答案 0 :(得分:2)

你只是在没有指定条件的情况下放置or语句就犯了一个错误。您必须指定另一个条件,而不仅仅是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 指出。

希望这有帮助!