Python将输入与布尔表达式进行比较

时间:2016-06-05 18:30:41

标签: python boolean

python新手。我正在写这段代码而且我不能为我的生活让我的程序打印else语句(yourName,'需要练习')当游泳和骑自行车的输入是'Y'和'N'的组合。我做错了什么?

def main():

    yourName = input("What is the your name? ")
    swim = input("Can you swim <Y>es or <N>o? ")
    cycling = input("Can you cycle <Y>es  or <N>o? ")

    if swim and cycling is 'Y' or swim and cycling is 'y':
            print(yourName, 'is an athlete.')
    elif swim and cycling is 'N' or swim and cycling is 'n':
        print(yourName,'shows potential.')
    else:
        print(yourName,'needs practise')

main()

3 个答案:

答案 0 :(得分:1)

您需要将条件更改为:

 if swim is 'Y' and cycling is 'Y' or swim is 'y' and cycling is 'y':

在python中,对于上面的例子, 如果游泳:  将意味着游泳是否存在,在这种情况下是真的。

答案 1 :(得分:0)

你可以这样做:

if swim.lower() == <char> <conditional operator> cycling.lower() == <char> :

char在哪里&#39; y&#39;或者&#39; n&#39;。

def main():

    yourName = input("What is the your name? ")
    swim = input("Can you swim <Y>es or <N>o? ")
    cycling = input("Can you cycle <Y>es  or <N>o? ")

    is_swim = swim.lower()
    is_cycle = cycling.lower()

    if is_swim == 'y' and is_swim == 'y':
            print(yourName, 'is an athlete.')
    elif is_swim == 'y' or is_cycle == 'y':
        print(yourName,'shows potential.')
    else:
        print(yourName,'needs practise')

main()

str.lower()将字符串转换为小写。

答案 2 :(得分:0)

你还没有在这里完全明确你所希望的逻辑,但如果目标是打印并显示出潜在的&#39;如果是游泳或骑自行车,则#39;是运动员&#39;如果两者都需要练习&#39;如果不是,则以下代码是更易读的选项。

def main():

    yourName = input("What is the your name? ")
    swim = input("Can you swim <Y>es or <N>o? ")
    cycling = input("Can you cycle <Y>es  or <N>o? ")

    swims = swim and swim.upper() == "Y"
    cycles = cycling and cycling.upper() == "Y"

    if swims and cycles:
        print(yourName, 'is an athlete.')
    elif (swims or cycles):
        print(yourName,'shows potential.')
    else:
        print(yourName,'needs practise')

main()