Python中的菜单驱动程序
菜单驱动程序简介
菜单驱动程序是一个通过显示选项列表(称为菜单)从用户那里获得输入的程序,用户可以从中选择他们的选项。处理菜单驱动程序的系统很普通,从由微处理器控制的洗衣机开始,到自动取款机(自动取款机)。以自动取款机为例,用户按单键指示交易类型(如果用户想要现金收据,或者需要对账单)。许多情况下,用户只需按一个键就可以指示要提取的现金数量。
菜单驱动系统在两个方面是有益的:首先,通过单次击键进行输入,这减少了系统太容易出现用户错误的机会。其次,菜单驱动系统限制了字符范围,导致输入的方式变得明确。因此,这两个特性使得整个系统非常用户友好。
在接下来的教程中,我们会发现一些用 Python 编写的菜单驱动程序。这些程序将让我们了解菜单驱动程序的不同方面,以及 Python 编程语言的不同库和模块。
那么,让我们开始吧。
使用函数计算不同形状的参数和面积
程序:
# defining functions
def p_circle(radius):
para = 2 * 3.14 * radius
print("Parameter of Circle:", para)
def p_rectangle(height, width):
para = 2 * (height + width)
print("Parameter of Rectangle:", para)
def p_square(side):
para = 4 * side
print("Parameter of Square:", para)
def a_circle(radius):
area = 3.14 * radius * radius
print("Area of Circle:", area)
def a_rectangle(height, width):
area = height * width
print("Area of Rectangle:", area)
def a_square(side):
area = side * side
print("Area of Square:", area)
# printing the starting line
print("WELCOME TO A SIMPLE MENSURATION PROGRAM")
# creating options
while True:
print("\nMAIN MENU")
print("1\. Calculate Parameter")
print("2\. Calculate Area")
print("3\. Exit")
choice1 = int(input("Enter the Choice:"))
if choice1 == 1:
print("\nCALCULATE PARAMETER")
print("1\. Circle")
print("2\. Rectangle")
print("3\. Square")
print("4\. Exit")
choice2 = int(input("Enter the Choice:"))
if choice2 == 1:
radius = int(input("Enter Radius of Circle:"))
p_circle(radius)
elif choice2 == 2:
height = int(input("Enter Height of Rectangle:"))
width = int(input("Enter Width of Rectangle:"))
p_rectangle(height, width)
elif choice2 == 3:
side = int(input("Enter Side of Square:"))
p_square(side)
elif choice2 == 4:
break
else:
print("Oops! Incorrect Choice.")
elif choice1 == 2:
print("\nCALCULATE AREA")
print("1\. Circle")
print("2\. Rectangle")
print("3\. Square")
print("4\. Exit")
choice3 = int(input("Enter the Choice:"))
if choice3 == 1:
radius = int(input("Enter Radius of Circle:"))
a_circle(radius)
elif choice3 == 2:
height = int(input("Enter Height of Rectangle:"))
width = int(input("Enter Width of Rectangle:"))
a_rectangle(height, width)
elif choice3 == 3:
side = int(input("Enter Side of Square:"))
a_square(side)
elif choice3 == 4:
break
else:
print("Oops! Incorrect Choice.")
elif choice1 == 3:
break
else:
print("Oops! Incorrect Choice.")
输出:
WELCOME TO A SIMPLE MENSURATION PROGRAM
MAIN MENU
1\. Calculate Parameter
2\. Calculate Area
3\. Exit
Enter the Choice:1
CALCULATE PARAMETER
1\. Circle
2\. Rectangle
3\. Square
4\. Exit
Enter the Choice:2
Enter Height of Rectangle:4
Enter Width of Rectangle:5
Parameter of Rectangle: 18
MAIN MENU
1\. Calculate Parameter
2\. Calculate Area
3\. Exit
Enter the Choice:2
CALCULATE AREA
1\. Circle
2\. Rectangle
3\. Square
4\. Exit
Enter the Choice:1
Enter Radius of Circle:2
Area of Circle: 12.56
MAIN MENU
1\. Calculate Parameter
2\. Calculate Area
3\. Exit
Enter the Choice:5
Oops! Incorrect Choice.
MAIN MENU
1\. Calculate Parameter
2\. Calculate Area
3\. Exit
Enter the Choice:3
说明:
在上面的例子中,我们定义了不同的函数来打印计算后的估计值。这些函数分别包括圆、矩形和正方形的参数和面积。然后我们打印了程序的标题:欢迎来到一个简单的测量程序。下面,我们使用无限的和循环来打印包含不同选项的主菜单。然后程序使用 if-elif-else 语句要求用户输入选择选项的整数。如果插入的整数不在选项列表中,程序还会引发 异常 。然后我们创建了两个不同的子菜单,将参数选项和区域选项分开。然后,我们在这些描述不同形状的子菜单中增加了一些选项。这些选项还采用不同的整数值,表示圆的半径、矩形的高度和宽度以及正方形的边。结果,成功地创建了菜单驱动程序,并且能够计算不同形状的参数和面积。
菜单驱动程序创建一个简单的计算器
在下面的菜单驱动程序中,我们将在 Python 中构建一个 简单计算器 。我们将使用无限而循环,功能同上。我们将设计一个菜单,允许用户与计算器功能交互,如加法、减法、乘法和除法。
让我们考虑以下程序的语法:
程序:
# defining addition function
def add(a, b):
sum = a + b
print(a, "+", b, "=", sum)
# defining subtraction function
def subtract(a, b):
difference = a - b
print(a, "-", b, "=", difference)
# defining multiplication function
def multiply(a, b):
product = a * b
print(a, "x", b, "=", product)
# defining division function
def divide(a, b):
division = a / b
print(a, "/", b, "=", division)
# printing the heading
print("WELCOME TO A SIMPLE CALCULATOR")
# using the while loop to print menu list
while True:
print("\nMENU")
print("1\. Sum of two Numbers")
print("2\. Difference between two Numbers")
print("3\. Product of two Numbers")
print("4\. Division of two Numbers")
print("5\. Exit")
choice = int(input("\nEnter the Choice: "))
# using if-elif-else statement to pick different options
if choice == 1:
print( "\nADDITION\n")
a = int( input("First Number: "))
b = int( input("Second Number: "))
add(a, b)
elif choice == 2:
print( "\nSUBTRACTION\n")
a = int( input("First Number: "))
b = int( input("Second Number: "))
subtract(a, b)
elif choice == 3:
print( "\nMULTIPLICATION\n")
a = int( input("First Number: "))
b = int( input("Second Number: "))
multiply(a, b)
elif choice == 4:
print( "\nDIVISION\n")
a = int( input("First Number: "))
b = int( input("Second Number: "))
divide(a, b)
elif choice == 5:
break
else:
print( "Please Provide a valid Input!")
输出:
WELCOME TO A SIMPLE CALCULATOR
MENU
1\. Sum of two Numbers
2\. Difference between two Numbers
3\. Product of two Numbers
4\. Division of two Numbers
5\. Exit
Enter the Choice: 1
ADDITION
First Number: 3
Second Number: 4
3 + 4 = 7
MENU
1\. Sum of two Numbers
2\. Difference between two Numbers
3\. Product of two Numbers
4\. Division of two Numbers
5\. Exit
Enter the Choice: 2
SUBTRACTION
First Number: 6
Second Number: 3
6 - 3 = 3
MENU
1\. Sum of two Numbers
2\. Difference between two Numbers
3\. Product of two Numbers
4\. Division of two Numbers
5\. Exit
Enter the Choice: 3
MULTIPLICATION
First Number: 8
Second Number: 2
8 x 2 = 16
MENU
1\. Sum of two Numbers
2\. Difference between two Numbers
3\. Product of two Numbers
4\. Division of two Numbers
5\. Exit
Enter the Choice: 4
DIVISION
First Number: 10
Second Number: 4
10 / 4 = 2.5
MENU
1\. Sum of two Numbers
2\. Difference between two Numbers
3\. Product of two Numbers
4\. Division of two Numbers
5\. Exit
Enter the Choice: 5
说明:
在上面的程序中,我们使用了与上一个程序几乎相似的程序。我们定义了加、减、乘、除等各种函数。然后,我们使用 while 循环向用户打印菜单列表,并使用 if-elif-else 语句返回用户需要的答案。结果,一个简单的计算器被成功创建,并执行一些基本的计算,如加法,减法,乘法和除法。
创建电话目录的菜单驱动程序
在下面的菜单驱动程序中,我们将使用不同的功能创建电话簿目录。我们将向电话簿目录添加以下功能:
存储人员的联系号码
使用人名搜索联系号码
让我们在下面的程序中实现这个想法:
程序:
# printing the heading of the program
print( "WELCOME TO THE PHONEBOOK DIRECTORY")
# creating a .txt file to store contact details
filename = "myphonebook.txt"
myfile = open(filename, "a+")
myfile.close
# defining main menu
def main_menu():
print( "\nMAIN MENU\n")
print( "1\. Show all existing Contacts")
print( "2\. Add a new Contact")
print( "3\. Search the existing Contact")
print( "4\. Exit")
choice = input("Enter your choice: ")
if choice == "1":
myfile = open(filename, "r+")
filecontents = myfile.read()
if len(filecontents) == 0:
print( "There is no contact in the phonebook.")
else:
print(filecontents)
myfile.close
enter = input("Press Enter to continue ...")
main_menu()
elif choice == "2":
newcontact()
enter = input("Press Enter to continue ...")
main_menu()
elif choice == "3":
searchcontact()
enter = input("Press Enter to continue ...")
main_menu()
elif choice == "4":
print("Thank you for using Phonebook!")
else:
print( "Please provide a valid input!\n")
enter = input( "Press Enter to continue ...")
main_menu()
# defining search function
def searchcontact():
searchname = input( "Enter First name for Searching contact record: ")
remname = searchname[1:]
firstchar = searchname[0]
searchname = firstchar.upper() + remname
myfile = open(filename, "r+")
filecontents = myfile.readlines()
found = False
for line in filecontents:
if searchname in line:
print( "Your Required Contact Record is:", end = " ")
print( line)
found = True
break
if found == False:
print( "The Searched Contact is not available in the Phone Book", searchname)
# first name
def input_firstname():
first = input( "Enter your First Name: ")
remfname = first[1:]
firstchar = first[0]
return firstchar.upper() + remfname
# last name
def input_lastname():
last = input( "Enter your Last Name: ")
remlname = last[1:]
firstchar = last[0]
return firstchar.upper() + remlname
# storing the new contact details
def newcontact():
firstname = input_firstname()
lastname = input_lastname()
phoneNum = input( "Enter your Phone number: ")
emailID = input( "Enter your E-mail Address: ")
contactDetails = ("[" + firstname + " " + lastname + ", " + phoneNum + ", " + emailID + "]\n")
myfile = open(filename, "a")
myfile.write(contactDetails)
print( "The following Contact Details:\n " + contactDetails + "\nhas been stored successfully!")
main_menu()
输出:
WELCOME TO THE PHONEBOOK DIRECTORY
MAIN MENU
1\. Show all existing Contacts
2\. Add a new Contact
3\. Search the existing Contact
4\. Exit
Enter your choice: 1
There is no contact in the phonebook.
Press Enter to continue ...
MAIN MENU
1\. Show all existing Contacts
2\. Add a new Contact
3\. Search the existing Contact
4\. Exit
Enter your choice: 2
Enter your First Name: Mark
Enter your Last Name: Henry
Enter your Phone number: 1234567890
Enter your E-mail Address: [email protected]
The following Contact Details:
[Mark Henry, 1234567890, [email protected]]
has been stored successfully!
Press Enter to continue ...
MAIN MENU
1\. Show all existing Contacts
2\. Add a new Contact
3\. Search the existing Contact
4\. Exit
Enter your choice: 3
Enter First name for Searching contact record: Mark
Your Required Contact Record is: [Mark Henry, 1234567890, [email protected]]
Press Enter to continue ...
MAIN MENU
1\. Show all existing Contacts
2\. Add a new Contact
3\. Search the existing Contact
4\. Exit
Enter your choice: 1
[Mark Henry, 1234567890, [email protected]]
Press Enter to continue ...
MAIN MENU
1\. Show all existing Contacts
2\. Add a new Contact
3\. Search the existing Contact
4\. Exit
Enter your choice: 4
Thank you for using Phonebook!
说明:
在上面的菜单驱动程序中,我们创建了一个电话簿目录,它可以在文本文件中存储新的联系人,显示存储的联系人,并允许用户搜索现有的号码。首先,我们创建了一个文本文件来存储联系方式。然后,我们定义了各种功能,以便添加、显示和搜索不同的联系人。我们还创建了不同的联系人详细信息字段,如名字、姓氏、手机号码和电子邮件地址。结果程序成功完成,同样的输出如上图所示。
结论
在上面的教程中,我们已经理解了菜单驱动编程的含义以及一些例子。我们创建了三个不同的程序,包括测量程序、一个简单的计算器和一个电话簿目录。除了这三个,还有许多其他程序可以创建。