【问题标题】:Program is stopping even though conditions haven't been met即使条件尚未满足,程序也会停止
【发布时间】:2018-04-24 13:30:08
【问题描述】:

即使我有它,当我按 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 ")`

【问题讨论】:

  • if c.upper() != 'N' or "Y" - is wrong, if c.upper() != 'N' 或 c.upper() != "Y"
  • 或:if c.upper() in {'Y', 'N'}: ...
  • if ... or "Y" 总是真实的,因为你的条件之一就是"Y",而"Y" 是真实的。你的意思是if c.upper() not in { 'N','Y'}:
  • @Basalex 你的意思是and,而不是or

标签: python python-3.x


【解决方案1】:

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

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

你也可以稍微重构代码,像这样组合最后两个ifs:

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

还有前两个ifs 像这样:

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

编辑

or 应替换为 and,否则该检查毫无意义。

感谢 khelwood 指出这一点。

希望这会有所帮助!

【讨论】:

  • c.upper() != 'N' or c.upper() != "Y" 始终为真。你的意思是and,而不是or
  • @khelwood 哦,很好,我在看语法错误,现在才更新
猜你喜欢
  • 2016-03-14
  • 2021-11-18
  • 2020-04-15
  • 2013-04-08
  • 2015-08-08
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多