Python教程-基于菜单的Python程序
介绍菜单驱动程序
菜单驱动程序是一种通过显示选项列表(称为菜单)来从用户那里获取输入的程序,用户可以从中选择他们的选项。处理菜单驱动程序的系统有各种各样,从由微处理器控制的洗衣机到自动取款机(ATM)。以ATM为例,用户按单个键来指示交易类型(用户是否需要一张现金收据,或者需要账户对账单)。对于许多情况,用户按单个键来指示取款金额。
菜单驱动系统有两个好处:首先,通过单个按键输入,减少了系统对用户错误的敏感性。其次,菜单驱动系统限制了字符范围,使输入变得明确无误。因此,这两个特性使整个系统非常用户友好。
在接下来的教程中,我们将了解一些用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
解释:
在上面的示例中,我们定义了不同的函数来打印计算后的估计值。这些函数包括圆、矩形和正方形的参数和面积。然后,我们打印了程序的标题,即欢迎使用简单的测量程序。在此之下,我们使用无限的while循环来打印包含不同选项的主菜单。然后,程序使用if-elif-else语句要求用户输入整数以选择选项。如果插入的整数不在选项列表中,程序将引发异常。然后,我们创建了两个不同的子菜单,分别描述参数选项和面积选项。然后,我们在这些子菜单中添加了一些更多的选项,描述不同的形状。这些选项还接受不同的整数值,表示圆的半径、矩形的高度和宽度,以及正方形的边长。结果,菜单驱动程序成功创建,并能够计算不同形状的参数和面积。
创建一个简单计算器的菜单驱动程序
在下面的菜单驱动程序中,我们将构建一个简单的Python计算器。我们将使用无限的while循环和与上面相同的函数。我们将设计一个菜单,允许用户与计算器功能进行交互,如加法、减法、乘法和除法。
让我们考虑以下程序的语法:
程序:
# 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: iammark@example.com
The following Contact Details:
[Mark Henry, 1234567890, iammark@example.com]
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, iammark@example.com]
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, iammark@example.com]
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!
解释:
在上面的菜单驱动程序中,我们创建了一个电话簿目录,可以将新联系存储在文本文件中,显示存储的联系方式,并允许用户搜索现有号码。首先,我们创建一个文本文件来存储联系详细信息。然后,我们定义了各种函数,用于添加、显示和搜索不同的联系人。我们还创建了不同的联系人详细信息字段,如名字、姓氏、手机号码和电子邮件地址。结果,程序成功完成,其输出如上所示。
结论
在上面的教程中,我们理解了菜单驱动编程的含义,以及一些示例。我们创建了三个不同的程序,包括测量程序、简单计算器和电话簿目录。除了这三个示例之外,还可以创建许多其他程序。