首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python比较输入和布尔表达式

Python比较输入和布尔表达式
EN

Stack Overflow用户
提问于 2016-06-05 18:30:41
回答 3查看 63关注 0票数 1

刚接触到蟒蛇。我正在编写这段代码,在我的一生中,当游泳和自行车的输入是'Y‘和'N’的组合时,我无法让我的程序打印code语句(yourName,‘’)。我做错什么了?

代码语言:javascript
运行
复制
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()
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-06-05 18:50:13

你可以这样做:

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

其中char是'y‘或'n’。

代码语言:javascript
运行
复制
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()将字符串转换为小写。

票数 0
EN

Stack Overflow用户

发布于 2016-06-05 18:39:00

您需要将条件更改为:

代码语言:javascript
运行
复制
 if swim is 'Y' and cycling is 'Y' or swim is 'y' and cycling is 'y':

在python中,对于上面的例子,如果游泳:将表示是否存在游泳,在本例中,这是正确的。

票数 1
EN

Stack Overflow用户

发布于 2016-06-05 18:51:36

在这里,你还没有完全清楚你想要的逻辑,但如果目标是打印“显示潜力”(如果是游泳或自行车的话),如果两者都是运动员,那么“需要练习”(如果两者都没有),下面的代码是一个更易读的选项。

代码语言:javascript
运行
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37645375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档