2

我是 Python 新手,目前正在使用 IF 语句做一些工作。这是我目前所拥有的......

print("Hello")
myName = input("What is your name?")
print("Hello " +myName)
myAge = int(input("How old are you?"))
if myAge <=18:
    myResponse = input("You must still be at school?")
    if myResponse == "Yes" or "yes" or "YES" or "Y" or "yEs" or "y":
        mySchool = input("What school do you go to?")
        print (mySchool, "that is a good school I hear")
    if myResponse == "No" or "n" or "N" or "NO":
        print("Lucky you, you have lots of free time!")
if myAge >=19:
    myResponse = input("You must have a job?")
    if myResponse == "Yes" or "yes" or "YES" or "Y" or "yEs" or "y":
        myWork = input("What do you do?")
        print (myWork, "Thats a tough job")
    if myResponse == "No" or "n" or "N" or "NO":
        print("Lucky you, you have lots of free time!")

我希望用户能够用一个单词的答案来回答问题,但是程序可以识别各种选项,例如“否”、“否”和“否”或“是”、“是”和“是的”。

我刚刚想出了上面看到的这种方法,但是应该有更好的方法吗?

请记住,我对此很陌生,所以这可能是一个愚蠢的问题。任何帮助将不胜感激。

4

4 回答 4

5

这个条件检查 myRespone 是yesor"y"并且不区分大小写(意味着yes,YeS和其他都是有效的)

myResponse.lower() in ["yes","y"]
于 2013-07-31T11:53:59.290 回答
2

尝试这个:

if myResonse.lower() == "yes":
    etc
于 2013-07-31T11:54:51.370 回答
2

该问题专门要求以“是”或“否”的形式提供不同大小写的答案(未提及“y”或“n”)。考虑到这一点,我们可以执行以下操作,小心删除任何多余的空格:

if myresponse.strip().lower() == "yes":
    # if yes, do something

同样:

if myresponse.strip().lower() == "no":
    # if no, do something else
于 2013-07-31T11:55:05.557 回答
1

使用字符串函数:

if myResponse.upper() == 'NO':
    # do something

或者:

if myResponse.lower() == 'no':
    #do something
于 2013-07-31T11:54:08.370 回答