Python - 在菜单上重用用户输入

时间:2014-03-29 05:16:47

标签: python class python-2.7 python-3.x menu

实现此目的的最佳方法是什么 - 在菜单上重用用户输入? 这是我的示例代码:

def input():
    user = raw_input('user: ')
    passwd = getpass.getpass('passwd: ')
    return (user,passwd)

def function1():
    user, passwd, vcenter = input() 
do something

def function2():
    user, passwd, vcenter = input() 
do something

def function3():
    user, passwd, vcenter = input()     
    do something

def main():
    while True:
        if choice == 1:
            function1()
        elif choice == 2:
            function2()
        elif choice == 3:
            function3()
        else:
            print 'Choose from the options only!'
        break

1 个答案:

答案 0 :(得分:0)

我想我明白你的意思,你想在while循环中使用input()一次,而不是在每个函数中重复调用它。如果是这样我建议这个解决方案:

def input():
    user = raw_input('user: ')
    passwd = getpass.getpass('passwd: ')
    return (user,passwd)

def function1(param):
    user, passwd = param
    do something

def function2(param):
    user, passwd = param
    do something

def function3(param):
    user, passwd = param
    do something

def main():
    while True:
        if choice in [1,2,3]:
            param = input() 
        if choice == 1:
            function1(param)
        elif choice == 2:
            function2(param)
        elif choice == 3:
            function3(param)
        else:
            print 'Choose from the options only (1, 2, 3): '
        break

希望这会有所帮助。