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 語句返回用戶需要的答案。結果,一個簡單的計算器被成功創建,並執行一些基本的計算,如加法,減法,乘法和除法。

創建電話目錄的菜單驅動程序

在下面的菜單驅動程序中,我們將使用不同的功能創建電話簿目錄。我們將向電話簿目錄添加以下功能:

  1. 存儲人員的聯繫號碼
  2. 使用人名搜索聯繫號碼

讓我們在下面的程序中實現這個想法:

程序:


# 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!

說明:

在上面的菜單驅動程序中,我們創建了一個電話簿目錄,它可以在文本文件中存儲新的聯繫人,顯示存儲的聯繫人,並允許用戶搜索現有的號碼。首先,我們創建了一個文本文件來存儲聯繫方式。然後,我們定義了各種功能,以便添加、顯示和搜索不同的聯繫人。我們還創建了不同的聯繫人詳細信息字段,如名字、姓氏、手機號碼和電子郵件地址。結果程序成功完成,同樣的輸出如上圖所示。

結論

在上面的教程中,我們已經理解了菜單驅動編程的含義以及一些例子。我們創建了三個不同的程序,包括測量程序、一個簡單的計算器和一個電話簿目錄。除了這三個,還有許多其他程序可以創建。


原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/129960.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
簡單一點的頭像簡單一點
上一篇 2024-10-03 23:27
下一篇 2024-10-03 23:27

相關推薦

  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29

發表回復

登錄後才能評論