python如何编写菜单

原创
admin 11小时前 阅读数 1 #Python

Python编写菜单指南

Python是一种高级编程语言,支持多种编程范式,包括面向对象编程和函数式编程,在Python中,可以使用各种方法创建菜单,以下是Python编写菜单的一些常见方法:

1、使用print函数打印菜单

Python中的print函数可用于在控制台上打印文本,您可以使用print函数打印菜单项,以便用户可以选择。

print("1. 选项1")
print("2. 选项2")
print("3. 退出")

2、使用input函数获取用户输入

Python中的input函数可用于获取用户的输入,您可以使用input函数获取用户选择的菜单项。

choice = input("请选择一个选项:")

3、使用循环和条件语句实现交互式菜单

您可以使用循环和条件语句实现交互式菜单,您可以使用while循环和if语句创建一个无限循环的菜单,直到用户选择退出选项。

while True:
    print("1. 选项1")
    print("2. 选项2")
    print("3. 退出")
    choice = input("请选择一个选项:")
    if choice == "1":
        print("您选择了选项1")
    elif choice == "2":
        print("您选择了选项2")
    elif choice == "3":
        break
    else:
        print("无效的选项")

4、使用类创建交互式菜单

您可以使用类创建一个交互式菜单,类可以包含菜单项和逻辑代码,以便在用户选择菜单项时执行相应的操作。

class Menu:
    def __init__(self):
        self.options = ["选项1", "选项2", "退出"]
        self.current_option = 0
    
    def display(self):
        print(self.current_option + 1, self.options[self.current_option])
    
    def get_choice(self):
        while True:
            choice = input("请选择一个选项:")
            if choice == str(self.current_option + 1):
                return int(choice) - 1
            elif choice == "q":
                return None
            else:
                print("无效的选项")
    
    def run(self):
        while True:
            self.display()
            choice = self.get_choice()
            if choice is None:
                break
            elif choice == 0:
                print("您选择了选项1")
            elif choice == 1:
                print("您选择了选项2")
            else:
                print("无效的选项")
            self.current_option = choice % len(self.options) - 1 + len(self.options) // 2 - 1 + self.current_option // len(self.options) * len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_option % len(self.options) // 2 - 1 + len(self.options) // 2 - 1 + self.current_
热门