菜單驅動程序簡介
菜單驅動程序是一個通過顯示選項列表(稱為菜單)從用戶那里獲得輸入的程序,用戶可以從中選擇他們的選項。處理菜單驅動程序的系統很普通,從由微處理器控制的洗衣機開始,到自動取款機(自動取款機)。以自動取款機為例,用戶按單鍵指示交易類型(如果用戶想要現金收據,或者需要對賬單)。許多情況下,用戶只需按一個鍵就可以指示要提取的現金數量。
菜單驅動系統在兩個方面是有益的:首先,通過單次擊鍵進行輸入,這減少了系統太容易出現用戶錯誤的機會。其次,菜單驅動系統限制了字符范圍,導致輸入的方式變得明確。因此,這兩個特性使得整個系統非常用戶友好。
在接下來的教程中,我們會發現一些用 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!
說明:
在上面的菜單驅動程序中,我們創建了一個電話簿目錄,它可以在文本文件中存儲新的聯系人,顯示存儲的聯系人,并允許用戶搜索現有的號碼。首先,我們創建了一個文本文件來存儲聯系方式。然后,我們定義了各種功能,以便添加、顯示和搜索不同的聯系人。我們還創建了不同的聯系人詳細信息字段,如名字、姓氏、手機號碼和電子郵件地址。結果程序成功完成,同樣的輸出如上圖所示。
結論
在上面的教程中,我們已經理解了菜單驅動編程的含義以及一些例子。我們創建了三個不同的程序,包括測量程序、一個簡單的計算器和一個電話簿目錄。除了這三個,還有許多其他程序可以創建。