【问题标题】:New at Python need some guidance with IF statementsPython 新手需要一些关于 IF 语句的指导
【发布时间】:2018-07-04 00:06:57
【问题描述】:

问:代码运行但只打印 else 语句... 任何帮助表示赞赏。

fruit = str()
favorite_fruits = ["mango", "kiwi", "pineapple"]
if fruit in favorite_fruits is "mango":
    print('You really like ' + fruit + '.')
if fruit in favorite_fruits is "kiwi":
    print('You really like ' + fruit + '.')
if fruit in favorite_fruits is "pineapple":
    print('You really like ' + fruit + '.')
if fruit in favorite_fruits is "apple":
    print('You really like' + fruit + '.')
else:
    print('Your going to starve.')

【问题讨论】:

  • fruit in favorite_fruits is "apple" 不会做任何有意义的事情,但我什至无法猜测您认为这意味着什么,尤其是考虑到苹果不在该列表中。
  • 苹果参考只是为了表明它不会打印。

标签: python python-3.x


【解决方案1】:

str() 每次都返回 ''。所以fruit 始终是'',它不满足任何if 语句。

您的 if 语句也已关闭。您可以检查fruit 是否在favorite_fruits 中,然后打印:

fruit = "mango"
favorite_fruits = ["mango", "kiwi", "pineapple"]

if fruit in favorite_fruits:
    print('You really like ' + fruit + '.')
else:
    print('Your going to starve.')

如果您想要用户输入,请使用input 而不是硬编码fruit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多