Python 中 if 语句的问题

Problems with if statements in Python

我是新 python 用户,一直在尝试将用户输入集成到更简单的代码中。原始代码如下所示。

原创 ================================================ ====== ==============

is_male=True
is_tall=False
if is_male and is_tall:
    print("User is male and tall.")
elif is_male and not(is_tall):
    print("User is male and short.")
elif not(is_male) and is_male:
    print("User is female and tall.")
else:
    print("User is female and short")

这是我想要的方式,但我希望用户能够输入此信息。但是,我 运行 遇到一个问题,即控制台始终显示“用户是男性且高大”。我下面的新代码有什么问题?非常感谢。

修改

is_male=input("You are male. True or False?")
if is_male == "True": 
    is_male == True
elif is_male == "False":
    is_male == False
else:
    print("Please enter True or False.")

is_tall=input("You are tall. True or False?")
if is_tall == "True": 
    is_tall == True
elif is_tall == "False":
    is_tall == False
else:
    print("Please enter True or False.")

is_male=True
is_tall=False
if is_male and is_tall:
    print("User is male and tall.")
elif is_male and not(is_tall):
    print("User is male and short.")
elif not(is_male) and is_male:
    print("User is female and tall.")
else:
    print("User is female and short")

您应该删除以下行:

is_male=True
is_tall=False

它们会覆盖用户选择的任何内容,从而使您的所有输入都变得无用 ;)

问题出在作业上。您正在使用双等号 == 而非单个等号 =.

来赋值

is_male=input("You are male. True or False?")
if is_male == "True": 
    is_male = True # This should just be single '='
elif is_male == "False":
    is_male = False # This should just be single '='
else:
    print("Please enter True or False.")

is_tall=input("You are tall. True or False?")
if is_tall == "True": 
    is_tall = True # This should just be single '='
elif is_tall == "False":
    is_tall = False # This should just be single '='
else:
    print("Please enter True or False.")

除此之外,我相信这些行只是错误添加的。请删除那些 -

is_male=True
is_tall=False

最后,你的比较应该是-

if is_male and is_tall:
    print("User is male and tall.")
elif is_male and ( not is_tall):
    print("User is male and short.")
elif (not is_male) and is_tall: # fix the typo here.. 
    print("User is female and tall.")
else:
    print("User is female and short")

在第二个 elif 中,您再次测试 is_male 而不是 is_tall