首页 > 解决方案 > 如何在python中添加if else语句以及函数定义

问题描述

很抱歉打扰我刚开始学习python的编码。我只是在python中自己创建了一些代码,没有错误显示。但是为什么 if else 语句没有执行。有人可以帮忙吗?

代码:

def name(f_name, age):
    return f"Hi, {f_name} {age}"
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")


person = name("Aditya", 17)
print(person)

标签: pythonif-statement

解决方案


在您的第 2 行,您使用了“return”。这意味着下面的代码不会被执行。您应该将代码行 2 移动到函数的末尾,例如

def name(f_name, age):
    # this code has removed
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")

    return f"Hi, {f_name} {age}"

推荐阅读