Python:功能菜单不起作用

时间:2015-11-27 21:13:25

标签: python python-2.7 menu

我在使用菜单时遇到问题,该菜单允许用户选择要调用的函数。问题的一部分是,当我运行程序时,它从头开始(而不是调用菜单函数),另一部分是我不知道如何传递表和行中的行数和列数对其余人的第一个功能(当我尝试它时说它们没有被定义)。该程序应该使用表格加密和解密文本。

3 个答案:

答案 0 :(得分:0)

首先,您需要一个main函数来运行您正在执行的操作。 该main函数将保存表,nc和nr的变量。 在主要功能:
- 创建一个名为at_menu的变量。将其设置为true。
- 创建一个" while(at_menu):"循环将始终返回菜单。
- 在while循环中输入你的代码来征求选项。
- 使用单独的if / elif / else语句来捕获选项。
- 表table(),encrypt()和decrypt()的返回值将重新分配主函数中的变量值。

这样的事情:

def get_option()
    #code to request option, validate it is valid
    return option

def table():
    # Your table code
    return tb, nc, nr

def encrypt( tb, nc, nr ):
    # your code

def decrypt( tb, nc, nr ):
    # your code

def main():
    option = None
    at_menu = true
    table = None
    nc = None
    nr = None
    while( at_menu ):
        option = get_option()
        if option == 1:
            ret_tup = table()
            table = ret_tup[0]
            nc = ret_tup[1]
            nr = ret_tup[2] # magic numbers bad
        elif option == 2:
            # should add code to confirm table is not None.
            encrypt( table, nc, nr )
        elif option == 3:
            # should add code to confirm table is not None and it has been encrypted
            decrypt( table, nc, nr )
        elif option == 4:
            at_menu = false

答案 1 :(得分:0)

为了将一个变量从一个函数传递给另一个函数,它需要是''global''。一种简单的方法是在所有函数之外初始化变量,并让所有函数调用它。这样它将在所有函数中定义。

答案 2 :(得分:0)

这是一个Class示例,我充实了一些基础知识,随时可以适应您的需求。这里的关键是所有'全局'变量(nc,nr和table)只是存储为类属性,以便稍后由类成员函数访问(即加密,解密)。

import copy, sys

class MyApp(object):

    message = '''
        Choose:
        1. Build a table
        2. Encrypt
        3. Decrypt
        4. End
        '''

    opts = ['table', 'encrypt', 'decrypt', 'exit_']

    def __init__(self):

        self.at_menu = True
        self.main()

    def main(self):

        while self.at_menu:
            try:
                choice = raw_input(MyApp.message)
                # Executes the item in the list at the selected
                # option -1 (since python is base 0 by default)
                getattr(self, MyApp.opts[int(choice)-1])()

            except (KeyError, ValueError, IndexError):
                print 'Wrong choice'
            except (KeyboardInterrupt, SystemExit):
                self.exit_

    def exit_(self):
        self.at_menu=False

    def table(self):

        self.nc = int(raw_input('Input number of columns: '))
        self.nr = int(raw_input('Input number of rows: '))

        row = [None for i in range(0,self.nc+1)]
        self.table = [copy.deepcopy(row) for i in range(0,self.nr+1)]
        for ch in range (1,self.nc+1):
            self.table[0][ch] = raw_input("Column Header {}: ".format(ch))

        for rh in range(1,self.nr+1):
            self.table[rh][0] = raw_input("Row Header {}: ".format(rh))

        for i in range(1,self.nr+1):
            for j in range(1,self.nc+1):
                self.table[i][j] = raw_input("Data {}{}: ".format(i,j))

        print str(self.table)

    def encrypt(self):

        #code using the class vars self.nc, self.nr, and etc
        pass

    def decrypt(self):

        #code using the class vars self.nc, self.nr, and etc
        pass

if __name__ == '__main__':
    MyApp()