即使在if语句为真后运行else语句的python代码

时间:2018-04-12 19:46:44

标签: python python-3.x

我正在学习python编程,并且正在经历If Else条件。 即使If语句为true,我的代码也会执行其他条件。

请检查以下代码:

age = int(input("Enter your Age (in years)"))
sex = input("Enter you Sex(M/F)")
if(sex == 'M'):
    if(age < 20):
        print("You are just a teen.")
    if(age >= 20 and age < 25):
        print("You are a young man now.")
    elif(age >=25 and age < 30):
        print("You are a mature man now")
    else:
        print("You are getting old")
if(sex == 'F'):
    if(age < 20):
        print("You are just a teen.")
    if(age >= 20 and age < 25):
        print("You are a young woman now.")
    elif(age >=25 and age < 30):
        print("You are a lady now")

在这里,如果我输入年龄为2且性别为M,则代码进入第一个条件并打印消息

  

“你只是一个团队”

除此之外,代码还运行else条件并打印

  

你老了

我不明白这种行为。我检查了缩进,所有缩进都是正确的。

4 个答案:

答案 0 :(得分:3)

你不小心把它变成了一个double,如果这会导致两个语句都被执行。

age = int(input("Enter your Age (in years)"))
sex = input("Enter you Sex(M/F)")
if(sex == 'M'):
    if(age < 20):
        print("You are just a teen.")
    elif(age >= 20 and age < 25): # notice now it is one if-elif block
        print("You are a young man now.")
    elif(age >=25 and age < 30):
        print("You are a mature man now")
    else:
        print("You are getting old")
if(sex == 'F'):
    if(age < 20):
        print("You are just a teen.")
    elif(age >= 20 and age < 25): # same here
        print("You are a young woman now.")
    elif(age >=25 and age < 30):
        print("You are a lady now")

答案 1 :(得分:1)

切换

if(age < 20):
    print("You are just a teen.")
if(age >= 20 and age < 25):
    print("You are a young man now.")

if(age < 20):
    print("You are just a teen.")
elif(age >= 20 and age < 25):
    print("You are a young man now.")

发生的事情是,如果性别= =&#39; M&#39;因为年龄不在20到25之间,所以没有得到满足。既然elif也没有完成,那么else块内部的运行是什么。

答案 2 :(得分:1)

在您提供的代码段中,else连接到第二个if语句:if(age >= 20 and age < 25):。第一个“if”执行正常,但是当第二个“if”失败时,它执行“else”。这可以通过将第二个“if”更改为“elif”来修复:

if(sex == 'M'):
    if(age < 20):
        print("You are just a teen.")
    elif(age >= 20 and age < 25):
        print("You are a young man now.")
    elif(age >=25 and age < 30):
        print("You are a mature man now")
    else:
        print("You are getting old")

答案 3 :(得分:1)

正在打印正确的输出。首先,它检查年龄是否少于20年,这是正确的,然后打印“你只是一个青少年。”。

if(sex == 'M'):
    if(age < 20):
        print("You are just a teen.")

之后它检查第二个'if'语句,然后'elif'然后它转到'else'并打印该语句,因为之前没有匹配。

if(age >= 20 and age < 25):
    print("You are a young man now.")
elif(age >=25 and age < 30):
    print("You are a mature man now")
else:
    print("You are getting old")

你可能在这里写了一个错字:

if(age >= 20 and age < 25):
    print("You are a young man now.")

可能你试图在这里使用'if'代替'elif'。

相关问题