如何在 Python 中结束函数,就像在 C++ 中使用“return”一样 [关闭]

Posted

技术标签:

【中文标题】如何在 Python 中结束函数,就像在 C++ 中使用“return”一样 [关闭]【英文标题】:How can I end a function in Python just like using "return" in c++ [closed] 【发布时间】:2017-12-20 16:26:19 【问题描述】:

您好,我是一名 Python 新手,我想像在 c++ 中一样使用“返回”功能。你知道如果我在c++中“return”,整个main函数就会停止,但是在Python中似乎“return”只能在function中使用。我尝试使用“exit”来替换它,但我不知道为什么它仍然执行“except”部分。我的代码有什么问题吗?非常感谢!

name=input("Please input your name? ")
print("Hello,", name)
year=input("Please input your birth year? ")
try:
    age=2007-int(year)
    if age <= 25:
        print("Welcome home! You have 5 chances to win the prize. ")
        for i in range (1, 5):
            luckynumber=input("Please input an random number? ")
            if int(luckynumber) == 66:
                print("Congratulation! Fist Prize!")
                exit(0)
            elif int(luckynumber) == 88:
                print("Not bad! Second Prize! ")
                exit(0)
            else:
                print("Best luck for next turn!")
        print("Sorry, you didn't win. ")
    else:
        print("Get out!")
except:
      print("Your birth-year or luckynumber must be an integer")

【问题讨论】:

"在Python中"return"似乎只能用在函数中。"在 C++ 中也是如此,所以不确定你在做什么。 为什么不把逻辑放在一个函数里面(包括适当的returns)然后调用这个函数? 也许你想读一本关于python的基础书?还是使用搜索引擎? 我认为这是一个很好的问题,'为什么它仍然执行“除外”部分。',有人知道吗? 供您参考:sys.exit() 正在通过引发(可拦截的)异常来结束程序。 【参考方案1】:

试试这个,这对我来说很好用

def my_func():
    name=raw_input("Please input your name? ")
    print("Hello,", name)
    year=raw_input("Please input your birth year? ")
    try:
        age=2007-int(year)
        if age <= 25:
            print("Welcome home! You have 5 chances to win the prize. ")
            for i in range (1, 5):
                luckynumber=input("Please input an random number? ")
                if int(luckynumber) == 66:
                    return("Congratulation! Fist Prize!")
                elif int(luckynumber) == 88:
                    return("Not bad! Second Prize! ")
                else:
                    print("Best luck for next turn!")
            return("Sorry, you didn't win. ")
        else:
            return("Get out!")
    except:
        return("Your birth-year or luckynumber must be an integer")

print my_func()

输出:

Please input your name? ***
('Hello,', '***')
Please input your birth year? 1985
Welcome home! You have 5 chances to win the prize. 
Please input an random number? 25
Best luck for next turn!
Please input an random number? 35
Best luck for next turn!
Please input an random number? 45
Best luck for next turn!
Please input an random number? 66
Congratulation! Fist Prize!

我不确定C++如果你想分别写函数和main分别可以这样写

def function_name(args):
    #function code
    pass

#main function
if __name__=="__main__":
    # calling the function
    function_name(1)

示例:

def my_func():
    name=raw_input("Please input your name? ")
    print("Hello,", name)
    year=raw_input("Please input your birth year? ")
    try:
        age=2007-int(year)
        if age <= 25:
            print("Welcome home! You have 5 chances to win the prize. ")
            for i in range (1, 5):
                luckynumber=input("Please input an random number? ")
                if int(luckynumber) == 66:
                    return("Congratulation! Fist Prize!")
                elif int(luckynumber) == 88:
                    return("Not bad! Second Prize! ")
                else:
                    print("Best luck for next turn!")
            return("Sorry, you didn't win. ")
        else:
            return("Get out!")
    except:
        return("Your birth-year or luckynumber must be an integer")

if __name__=="__main__":
    print my_func()

【讨论】:

谢谢你!有用。你能告诉我是否有像 C++ 一样的“主函数”python 吗? 如果可行,请您将我的答案标记为有用且正确的答案吗? 如果 name__=="__main": @Xu Haifeng 我已经使用 main 函数编辑了代码。请看一下,看看这是否是你要找的。下面的链接有一些关于主要***.com/questions/22492162/…的信息 如何标记它有用? ✔️把这个变成绿色?【参考方案2】:

退出功能由sys模块提供,需要导入:

import sys
sys.exit(0)

否则,您可以将代码包装在函数中并使用 return 语句:

def main():
    name=input("Please input your name? ")
    print("Hello,", name)
    year=input("Please input your birth year? ")
    try:
        age=2007-int(year)
        if age <= 25:
            print("Welcome home! You have 5 chances to win the prize. ")
            for i in range (1, 5):
                luckynumber=input("Please input an random number? ")
                if int(luckynumber) == 66:
                    print("Congratulation! Fist Prize!")
                    return
                elif int(luckynumber) == 88:
                    print("Not bad! Second Prize! ")
                    return
                else:
                    print("Best luck for next turn!")
            print("Sorry, you didn't win. ")
        else:
            print("Get out!")
    except:
          print("Your birth-year or luckynumber must be an integer")

if __name__ == '__main__':
    main()

作为旁注,当您删除 try/except 时,解释器将向您显示错误出现的位置和位置。 另一种选择是导入 traceback 模块并在 except 块中使用 traceback.print_exec()

【讨论】:

以上是关于如何在 Python 中结束函数,就像在 C++ 中使用“return”一样 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

python语言如何结尾?

我的代码就像在一个while循环中一样,即使它不是

如何在 C++ 中使用 CPR 库?

C : 使用 && 运算符时是不是存在“惰性求值”,就像在 C++ 中一样?

用VC写了一个文本编辑器,怎样将输入里面的关键字变色实现高亮状态,就像在VC里面写代码输入C++关键字那样

C++ 函数指针参数和类继承自动转换