如何退出功能

2024-05-31 04:48:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,虽然它是一个简单的程序,但我还是坚持了一点 我使用了“Return False”移出函数,但我想完全移出函数。如何做到这一点。 另外,如果我想从pythonshell运行这个脚本,还需要知道如何完成它。你知道吗

def menu():
    print "calculator using functions"
    print "Choose your option:"
    print " "
    print "1) Addition"
    print "2) Subtraction"
    print "3) Multiplication"
    print "4) Division"
    print "5) Quit calculator.py"
    print " "
    return input ("Choose your option: ")


def add(a,b):
    print a, "+", b, "=", a + b
    print " Do you want to continue: "
    decide=raw_input("yes or no: ")
    if decide== "no" or decide== 'n':
        print(" You have exited ")
        return False
    elif decide=='yes' or decide== 'y':
        menu()
    else:
        print "wrong choice!!!"
        return False

# this subtracts two numbers given
def sub(a,b):
    print b, "-", a, "=", b - a

# this multiplies two numbers given
def mul(a,b):
    print a, "*", b, "=", a * b

# this divides two numbers given
def div(a,b):
    print a, "/", b, "=", a / b


loop = 1
choice = 0
while loop == 1:
    choice = menu()
    if choice == 1:
        add(input("Add first No: "),input("Add second No: "))
    elif choice == 2:
        sub(input("Add first No: "),input("Add second No: "))
    elif choice == 3:
        mul(input("Add first No: "),input("Add second No: "))
    elif choice == 4:
        div(input("Add first No: "),input("Add second No: "))
    elif choice == 5:
        loop = 0

print "End of program!"

Tags: ornoaddfalseinputreturndefthis
3条回答

退出函数不必显式地return任何内容。当解释器到达函数块的末尾时,函数退出。你知道吗

在命令行中键入:

Python我的程序.py你知道吗

要从提示符运行程序,如果要使用特定的python shell(bash或cmd除外),则需要查看该特定shell的文档(例如http://www.dreampie.org/)。你知道吗

要退出函数,请使用:

return

要退出程序,请使用:

import sys
sys.exit(0)

您想使用exit。它退出程序。你知道吗

import sys

def spam():
    .
    .
    .
    if some_condition:
        sys.exit(0) # exits from the program
    .
    .
    .

相关问题 更多 >