将3个功能组合到一个程序中

时间:2019-02-23 17:18:54

标签: python python-3.x

我有一个编程问题,对于大多数人来说听起来很容易,但是我很困惑,无法解决。如果有人可以帮我解决这个问题,那将真的很有帮助。

我正在制作一个类似于银行模拟器的程序,它由一个类(Account)以及一些方法和函数组成。银行应该能够设置一个新帐户,提款,更改PIN码等。

不确定是否有任何问题与问题有关,但是无论如何,我现在要执行的是运行程序。我想包含3个功能:

menu() # Just prints the menu. Like "Hi! What to you want to do? 1. Withdrawal 2. Change PIN" and so on...

menu_choice(): # An input. Choose a number between 1-6
    choice = input("Choose a number!")
    execute(choice)

execute(choice) # A code with six "if":s that does different stuff depending on the menu_choice().

问题是:如何将这三个程序合并为一个程序?

我要打印菜单,然后执行菜单选择。应该重复这一操作,直到menu_choice()== 6为止,因为这是“结束程序”选项。

但是我该怎么做,就像是while循环之类的东西?

3 个答案:

答案 0 :(得分:1)

如果您想对命令进行无限递归,请执行以下操作:

while True: # while needs a condition that is True. True is obviously True. 1 < 2 would be True as well, 2 < 1 not.
    menu_choice()

如果要从该循环中突围,请在循环内使用break

如果您想运行命令n次,请执行以下操作:

for i in range(n):
    menu_choice()

其中i保存当前循环号。

答案 1 :(得分:0)

首先,在menu_choice()函数中添加一行:## 已编辑 ##

def menu():
    print("Hi! What to you want to do? 1. Withdrawal 2. Change PIN")

def execute(choice):
    if choice == 1:
        print("1") 
    elif choice == 2:
        print("2") 
    elif choice == 3:
        print("3") 
    elif choice == 4:
        print("4")
    elif choice == 5:
        print("5") 
    elif choice == 6:
        print("6") 
        return 1
    return 0

def menu_choice():
    menu()
    choice = int(input("Choose a number!"))
    should_the_loop_break = execute(choice)
    return should_the_loop_break

您可以通过两种方式调用menu_choice()方法:

1)无限循环:## 已编辑 ##

while True:
    should_the_loop_break = menu_choice()
    if should_the_loop_break == 1:
        break

2)给定编号的时间

for i in range(0,n):
    menu_choice()

让我知道它是否有效/出现错误!

PS:请忽略变量名的拼写错误。

答案 2 :(得分:0)

我宁愿重组代码,如下所示:

#Returns a number if input is valid and None otherwise
def get_choice():
    try:
        return int(input("choose a number! "))
    except ValueError:
        return None

def execute(choice):
    print("execute %i" % choice)

def main():
    while True:
        choice = get_choice()
        if choice is None: #make sure input is valid
            continue.      #ask again
        if choice != 6:
            execute(choice)
        else:
            break          #choice == 6

 main()

Main被实现为while循环。它在执行目标功能之前检查有效输入。它再次询问用户输入是否无效。只要选择的值不等于6,它就会运行。