【问题标题】:If and elif are not printingif 和 elif 不打印
【发布时间】:2012-07-30 21:12:34
【问题描述】:
print'Personal information, journal and more to come'
x = raw_input()
if x ==("Personal Information"): # wont print 
 print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN:  , SS:'
elif x ==("Journal"):  # wont print 
 read = open('C:\\python\\foo.txt' , 'r')
 name = read.readline()
 print (name)

我启动程序并显示"Personal information, journal and more to come",但是当我输入Personal informationjournal neither 时,它们会打印结果并且我没有收到任何错误。

【问题讨论】:

    标签: python printing if-statement


    【解决方案1】:

    当我输入个人信息或日记时

    嗯,是的。它不期望其中任何一个。你的情况是错误的。

    要执行不区分大小写的比较,请先将两者转换为相同的大小写。

    if foo.lower() == bar.lower():
    

    【讨论】:

    • ehhh 我想我需要一个更好的解释,我是初学者,在实际脚本中会是什么样子?您是否要使我的文件中的文本小写?还有什么酒吧
    • foobar这些神秘物体是什么??? O.o @EdwardLaPiere: foo 和 bar 只是示例变量。您可以将它们替换为您真正有兴趣比较的任何对象。
    • 还有一个问题,我如何循环代码,这样我就可以继续输入这两个选项,而不会出现错误提示未定义的内容?
    【解决方案2】:

    为我工作。你是用大写的 I 写“个人信息”吗?

    print'Personal information, journal and more to come'
    x = raw_input()
    if x == ("Personal Information"): # wont print
        print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN:  , SS:'
    elif x ==("Journal"):  # wont print
        read = open('C:\\python\\foo.txt' , 'r')
        name = read.readline()
        print (name)
    

    输出:

    [00:20: ~$] python py
    Personal information, journal and more to come
    Journal
    Traceback (most recent call last):
      File "py", line 8, in <module>
        read = open('C:\\python\\foo.txt' , 'r')
    IOError: [Errno 2] No such file or directory: 'C:\\python\\foo.txt'
    [00:20: ~$] python py
    Personal information, journal and more to come
    Personal Information
     Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN:  , SS:
    [00:20: ~$] 
    

    也许是格式?我使用了 4 个空格。

    【讨论】:

      【解决方案3】:

      当 if 语句需要个人信息时,您正在输入个人信息(以大写 I 表示信息)。

      你能做的(上面的伊格纳西奥正在逃避的事情)就是做:

      if x.lower() == ("Personal Information").lower():
      

      代替:

      if x == ("Personal Information"):
      

      那么任何情况下,“个人信息”、“个人信息”、“个人信息”等都会匹配并进入 if 语句。之所以会这样,是因为在执行的时候,它会取 x 的值,把它变成小写字符串,把字符串“个人信息”变成小写字符串,所以现在不管原来是什么情况,他们比较时两者都是小写。

      foo 和 bar 是示例,是编程中常见的编程术语。它只是任何变量的示例,x、y、z 等可以很容易地使用,但 foo 和 bar 只是可以引用的常用变量。

      【讨论】: