You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

菜单驱动程序中如何在if语句间实现函数参数传递?

Hey there! I see you're working on a menu-driven COVID testing management system, and you're stuck on passing patient data from the registration option (1) to the total patients count option (2). Let's break down how to fix this with two practical approaches that fit your code structure.

Approach 1: Use a Global Variable (Simple for Small Programs)

The easiest way to share data between functions is to use a global variable to store patient records. This works well for small scripts like yours.

Here's the modified code with this approach:

# Global list to store all registered patients
patients = []

def main():
    intro()
    loop = True
    while loop:
        print("\n<<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>>>")
        print("\nChoose your option below:")
        print("1 - Patient Registration")
        print("2 - Total Patients")
        print("3 - Total Sales")
        print("Q/q - Quit")
        choice = str(input("Your choice?")).strip()
        print("\n<<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>>>")
        menu(choice)

def intro():
    print("Welcome to CTI System.")
    print("This system is used to track and manage Covid-19 testing")

def patientRegistration():
    global patients  # Declare we're using the global patients list
    # Collect patient info (customize this with your actual fields)
    name = input("Enter patient name: ").strip()
    age = input("Enter patient age: ").strip()
    test_type = input("Enter test type (PCR/Antigen): ").strip().upper()
    
    # Add patient data to the global list (store as a dictionary for clarity)
    patients.append({
        "name": name,
        "age": age,
        "test_type": test_type
    })
    print("Patient registered successfully!")
    
    # Return to main menu if user chooses not to register another
    continue_reg = input("Register another patient? (Y/N): ").strip().upper()
    if continue_reg != "Y":
        return

def totalPatients():
    global patients
    print(f"\nTotal number of registered patients: {len(patients)}")

def totalSales():
    # Calculate sales based on test types (example pricing)
    pcr_cost = 120
    antigen_cost = 50
    total = 0
    for patient in patients:
        if patient["test_type"] == "PCR":
            total += pcr_cost
        elif patient["test_type"] == "ANTIGEN":
            total += antigen_cost
    print(f"\nTotal sales from tests: ${total:.2f}")

def menu(choice):
    if choice == '1':
        patientRegistration()
    elif choice == '2':
        totalPatients()  # Replaced your original testType call with the correct function
    elif choice == '3':
        totalSales()
    elif choice.upper() == 'Q':
        print("\nThank you for using this program.\n")
        exit()
    else:
        print("\nInvalid choice! Please select from the list of choices.\n")
        # Note: Your original loop=False here doesn't affect the main loop, so we removed it

How this works:

  • The patients global list lives outside all functions, so every function can access and modify it.
  • When a user registers a patient, patientRegistration() adds their data to the list.
  • When option 2 is selected, totalPatients() checks the length of the global list to get the total count.

Approach 2: Use a Class (Better for Scalable Programs)

If you plan to expand your system later (add more features, track more data), using a class to encapsulate your system's state is cleaner and more maintainable.

Here's the object-oriented version:

class CTISystem:
    def __init__(self):
        self.patients = []  # Instance variable to store patients (no globals needed)

    def intro(self):
        print("Welcome to CTI System.")
        print("This system is used to track and manage Covid-19 testing")

    def show_menu(self):
        print("\n<<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>>>")
        print("\nChoose your option below:")
        print("1 - Patient Registration")
        print("2 - Total Patients")
        print("3 - Total Sales")
        print("Q/q - Quit")
        return str(input("Your choice?")).strip()

    def patient_registration(self):
        name = input("Enter patient name: ").strip()
        age = input("Enter patient age: ").strip()
        test_type = input("Enter test type (PCR/Antigen): ").strip().upper()
        
        self.patients.append({
            "name": name,
            "age": age,
            "test_type": test_type
        })
        print("Patient registered successfully!")
        
        continue_reg = input("Register another patient? (Y/N): ").strip().upper()
        if continue_reg != "Y":
            return

    def total_patients(self):
        print(f"\nTotal number of registered patients: {len(self.patients)}")

    def total_sales(self):
        pcr_cost = 120
        antigen_cost = 50
        total = sum(pcr_cost if p["test_type"] == "PCR" else antigen_cost for p in self.patients)
        print(f"\nTotal sales from tests: ${total:.2f}")

    def run(self):
        self.intro()
        loop = True
        while loop:
            choice = self.show_menu()
            print("\n<<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>>>")
            if choice == '1':
                self.patient_registration()
            elif choice == '2':
                self.total_patients()
            elif choice == '3':
                self.total_sales()
            elif choice.upper() == 'Q':
                print("\nThank you for using this program.\n")
                loop = False
            else:
                print("\nInvalid choice! Please select from the list of choices.\n")

# Run the system
if __name__ == "__main__":
    cti_system = CTISystem()
    cti_system.run()

How this works:

  • All patient data is stored in the patients instance variable of the CTISystem class.
  • Every method in the class can access this data directly via self.patients, so no need for global variables.
  • The run() method handles the main loop, keeping all logic encapsulated in one place.

Quick Fix Note for Your Original Code

In your original menu() function, the loop = False line doesn't affect the main loop in main() (since loop is a local variable in main). Removing it ensures users get another chance to input a valid option after making a mistake.

内容的提问来源于stack exchange,提问作者Kamil Dominorky Magno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:37:29