【问题标题】:The last else clause in python does not work [duplicate]python中的最后一个else子句不起作用[重复]
【发布时间】:2016-03-27 15:16:25
【问题描述】:

当我运行该程序并将性别输入为其他任何内容而不是男性或女性时,该程序无法按预期运行。我挣扎了一天,想不通。另外,我怎样才能在调用后放置该函数并仍然使程序运行?我读过一个 main 函数,但不知道如何用它修改代码。

from sys import exit
birthdays = {'Alice': 'April 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}

def dateOfBirth():
    bday = raw_input("> ")
    birthdays[name] = bday
    print "Database records updated."
    print "The number of records is now " + str(len(birthdays)) + "."
    print birthday`enter code here`s
    exit(0)

while True:
    print "Enter a name: (blank to quit)"
    name = raw_input("> ")

    if name == '':
        exit(0)

    if name in birthdays:
        print birthdays[name] + " is the birthday of " + name + "."
        exit(0)

    else:
        print "I do not have the birthday information for " + name + "."
        print " What is the sex?"
        gender = raw_input("> ")
        if gender == 'male':
            print "What is his birthday?"
            dateOfBirth()
        elif gender == 'female' or 'Female':
            print "What is her birthday?"
            dateOfBirth()
        else:
            print " The gender is not recognised. Anyway we will continue." 
            dateOfBirth()

【问题讨论】:

  • does not work as expected,怎么会这样?
  • 看来你必须坚持在这里==> while True: name = raw_input("> ") 。暂时没有办法走出去
  • 你可以用return代替exit(0)
  • @obayhan - 是的,exit(0) 同时所有代码都缩进了,所以这不是问题
  • @cricket_007 不,如果你检查历史,我写的时候就没有。

标签: python


【解决方案1】:

改变这个:

elif gender == 'female' or 'Female':

到这里:

elif gender in ('female', 'Female'):

或者我会建议:

elif gender.lower()=='female':

你有什么

elif gender == 'female' or 'Female':

本质上是如果性别是女性,或者如果字符串“Female”是非空的,则为else。无论gender 的值是多少,这始终是正确的。

【讨论】:

  • 谢谢,问题的第二部分呢。
  • 参见this question 了解如何使用main 函数。
猜你喜欢
  • 2020-04-29
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
相关资源
最近更新 更多