菜單驅(qū)動(dòng)程序簡(jiǎn)介
菜單驅(qū)動(dòng)程序是一個(gè)通過顯示選項(xiàng)列表(稱為菜單)從用戶那里獲得輸入的程序,用戶可以從中選擇他們的選項(xiàng)。處理菜單驅(qū)動(dòng)程序的系統(tǒng)很普通,從由微處理器控制的洗衣機(jī)開始,到自動(dòng)取款機(jī)(自動(dòng)取款機(jī))。以自動(dòng)取款機(jī)為例,用戶按單鍵指示交易類型(如果用戶想要現(xiàn)金收據(jù),或者需要對(duì)賬單)。許多情況下,用戶只需按一個(gè)鍵就可以指示要提取的現(xiàn)金數(shù)量。
菜單驅(qū)動(dòng)系統(tǒng)在兩個(gè)方面是有益的:首先,通過單次擊鍵進(jìn)行輸入,這減少了系統(tǒng)太容易出現(xiàn)用戶錯(cuò)誤的機(jī)會(huì)。其次,菜單驅(qū)動(dòng)系統(tǒng)限制了字符范圍,導(dǎo)致輸入的方式變得明確。因此,這兩個(gè)特性使得整個(gè)系統(tǒng)非常用戶友好。
在接下來的教程中,我們會(huì)發(fā)現(xiàn)一些用 Python 編寫的菜單驅(qū)動(dòng)程序。這些程序?qū)⒆屛覀兞私獠藛悟?qū)動(dòng)程序的不同方面,以及 Python 編程語言的不同庫和模塊。
那么,讓我們開始吧。
使用函數(shù)計(jì)算不同形狀的參數(shù)和面積
程序:
# 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
說明:
在上面的例子中,我們定義了不同的函數(shù)來打印計(jì)算后的估計(jì)值。這些函數(shù)分別包括圓、矩形和正方形的參數(shù)和面積。然后我們打印了程序的標(biāo)題:歡迎來到一個(gè)簡(jiǎn)單的測(cè)量程序。下面,我們使用無限的和循環(huán)來打印包含不同選項(xiàng)的主菜單。然后程序使用 if-elif-else 語句要求用戶輸入選擇選項(xiàng)的整數(shù)。如果插入的整數(shù)不在選項(xiàng)列表中,程序還會(huì)引發(fā) 異常 。然后我們創(chuàng)建了兩個(gè)不同的子菜單,將參數(shù)選項(xiàng)和區(qū)域選項(xiàng)分開。然后,我們?cè)谶@些描述不同形狀的子菜單中增加了一些選項(xiàng)。這些選項(xiàng)還采用不同的整數(shù)值,表示圓的半徑、矩形的高度和寬度以及正方形的邊。結(jié)果,成功地創(chuàng)建了菜單驅(qū)動(dòng)程序,并且能夠計(jì)算不同形狀的參數(shù)和面積。
菜單驅(qū)動(dòng)程序創(chuàng)建一個(gè)簡(jiǎn)單的計(jì)算器
在下面的菜單驅(qū)動(dòng)程序中,我們將在 Python 中構(gòu)建一個(gè) 簡(jiǎn)單計(jì)算器 。我們將使用無限而循環(huán),功能同上。我們將設(shè)計(jì)一個(gè)菜單,允許用戶與計(jì)算器功能交互,如加法、減法、乘法和除法。
讓我們考慮以下程序的語法:
程序:
# 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
說明:
在上面的程序中,我們使用了與上一個(gè)程序幾乎相似的程序。我們定義了加、減、乘、除等各種函數(shù)。然后,我們使用 while 循環(huán)向用戶打印菜單列表,并使用 if-elif-else 語句返回用戶需要的答案。結(jié)果,一個(gè)簡(jiǎn)單的計(jì)算器被成功創(chuàng)建,并執(zhí)行一些基本的計(jì)算,如加法,減法,乘法和除法。
創(chuàng)建電話目錄的菜單驅(qū)動(dòng)程序
在下面的菜單驅(qū)動(dòng)程序中,我們將使用不同的功能創(chuàng)建電話簿目錄。我們將向電話簿目錄添加以下功能:
存儲(chǔ)人員的聯(lián)系號(hào)碼
使用人名搜索聯(lián)系號(hào)碼
讓我們?cè)谙旅娴某绦蛑袑?shí)現(xiàn)這個(gè)想法:
程序:
# 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!
說明:
在上面的菜單驅(qū)動(dòng)程序中,我們創(chuàng)建了一個(gè)電話簿目錄,它可以在文本文件中存儲(chǔ)新的聯(lián)系人,顯示存儲(chǔ)的聯(lián)系人,并允許用戶搜索現(xiàn)有的號(hào)碼。首先,我們創(chuàng)建了一個(gè)文本文件來存儲(chǔ)聯(lián)系方式。然后,我們定義了各種功能,以便添加、顯示和搜索不同的聯(lián)系人。我們還創(chuàng)建了不同的聯(lián)系人詳細(xì)信息字段,如名字、姓氏、手機(jī)號(hào)碼和電子郵件地址。結(jié)果程序成功完成,同樣的輸出如上圖所示。
結(jié)論
在上面的教程中,我們已經(jīng)理解了菜單驅(qū)動(dòng)編程的含義以及一些例子。我們創(chuàng)建了三個(gè)不同的程序,包括測(cè)量程序、一個(gè)簡(jiǎn)單的計(jì)算器和一個(gè)電話簿目錄。除了這三個(gè),還有許多其他程序可以創(chuàng)建。