杰瑞科技汇

Python LargerDoses,如何高效学习Python?

Of course! The name "largerDoses" suggests a program that calculates the total amount of medication needed over a period, given a dose and frequency. This is a very practical and common use case for a simple Python script.

Python LargerDoses,如何高效学习Python?-图1
(图片来源网络,侵删)

Let's build a program called largerDoses that does this. We'll start with a basic version and then add more features to make it more robust and user-friendly.

Version 1: The Basic Script

This is the simplest version. It asks the user for a few key pieces of information and then prints the total.

# largerDoses.py - A simple medication calculator
def calculate_total_medication():
    """
    Calculates the total amount of medication needed.
    """
    try:
        # 1. Get user input
        dose_per_admin = float(input("Enter the dose per administration (e.g., 5 for 5mg): "))
        frequency_per_day = int(input("Enter how many times per day this dose is given: "))
        duration_days = int(input("Enter the duration of treatment in days: "))
        # 2. Perform the calculation
        daily_dose = dose_per_admin * frequency_per_day
        total_dose = daily_dose * duration_days
        # 3. Display the results
        print("\n--- Medication Summary ---")
        print(f"  Dose per administration: {dose_per_admin}mg")
        print(f"  Frequency: {frequency_per_day} times per day")
        print(f"  Daily total: {daily_dose}mg")
        print(f"  Treatment duration: {duration_days} days")
        print("--------------------------")
        print(f"-> Total medication required: {total_dose}mg")
    except ValueError:
        # This block runs if the user enters text instead of a number
        print("\nError: Invalid input. Please enter numbers only.")
# Run the function when the script is executed
if __name__ == "__main__":
    calculate_total_medication()

How to Run It:

  1. Save the code above into a file named largerDoses.py.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. Run the script with the command: python largerDoses.py

Example Interaction:

Enter the dose per administration (e.g., 5 for 5mg): 10
Enter how many times per day this dose is given: 2
Enter the duration of treatment in days: 14
--- Medication Summary ---
  Dose per administration: 10.0mg
  Frequency: 2 times per day
  Daily total: 20.0mg
  Treatment duration: 14 days
--------------------------
-> Total medication required: 280.0mg

Version 2: Adding More Features (Robustness & Reusability)

Let's improve the script. A good program should:

  • Handle bad input gracefully (e.g., negative numbers).
  • Be reusable in other parts of a larger application.
  • Have clear documentation.
# largerDoses_v2.py - A more robust medication calculator
def calculate_total_medication(dose_per_admin: float, frequency_per_day: int, duration_days: int) -> float:
    """
    Calculates the total amount of medication needed.
    Args:
        dose_per_admin: The amount of medication for a single dose.
        frequency_per_day: The number of doses administered per day.
        duration_days: The total number of days for the treatment.
    Returns:
        The total calculated dose. Returns 0 if any input is invalid.
    """
    # Validate inputs to ensure they are positive numbers
    if dose_per_admin <= 0 or frequency_per_day <= 0 or duration_days <= 0:
        print("Error: All values must be positive numbers.")
        return 0.0
    daily_dose = dose_per_admin * frequency_per_day
    total_dose = daily_dose * duration_days
    return total_dose
def get_user_input():
    """
    Handles user input and prompts for medication details.
    Returns a tuple of (dose, frequency, duration) or None if input fails.
    """
    try:
        dose = float(input("Enter the dose per administration (e.g., 5 for 5mg): "))
        frequency = int(input("Enter how many times per day this dose is given: "))
        duration = int(input("Enter the duration of treatment in days: "))
        return dose, frequency, duration
    except ValueError:
        print("\nError: Invalid input. Please enter valid numbers.")
        return None
def main():
    """
    Main function to run the medication calculator program.
    """
    print("--- Welcome to the LargerDoses Calculator ---")
    user_data = get_user_input()
    if user_data:
        dose, freq, days = user_data
        total_medication = calculate_total_medication(dose, freq, days)
        if total_medication > 0:
            print("\n--- Medication Summary ---")
            print(f"  Dose per administration: {dose}mg")
            print(f"  Frequency: {freq} times per day")
            print(f"  Daily total: {dose * freq}mg")
            print(f"  Treatment duration: {days} days")
            print("--------------------------")
            print(f"-> Total medication required: {total_medication}mg")
            print("--------------------------")
# This standard line ensures that main() is called only when the script is executed directly
if __name__ == "__main__":
    main()

Key Improvements in Version 2:

  1. Separation of Concerns: The logic is split into smaller, focused functions:
    • calculate_total_medication: Purely for the calculation. It can be imported and used in another script without any user interaction.
    • get_user_input: Handles all input and validation.
    • main: Orchestrates the flow of the program.
  2. Input Validation: The calculate_total_medication function now checks if the inputs are positive numbers. This prevents nonsensical results (like a negative total dose).
  3. Type Hinting: The function signatures include type hints (e.g., dose_per_admin: float). This helps developers understand what kind of data a function expects and returns.
  4. Error Handling: The try...except block is now neatly contained within get_user_input, making the code cleaner.

Version 3: The Full-Featured Application (Command-Line Arguments)

For a more professional tool, we can allow users to provide the information directly as command-line arguments. This is useful for scripting, automation, or quick calculations without interactive prompts.

Python LargerDoses,如何高效学习Python?-图2
(图片来源网络,侵删)

We'll use Python's built-in argparse module, which is the standard way to handle command-line arguments.

# largerDoses_v3.py - A command-line interface (CLI) for the calculator
import argparse
def calculate_total_medication(dose_per_admin: float, frequency_per_day: int, duration_days: int) -> float:
    """
    Calculates the total amount of medication needed.
    (Same function as in V2)
    """
    if dose_per_admin <= 0 or frequency_per_day <= 0 or duration_days <= 0:
        # argparse will handle the error display for us, so we just return 0
        return 0.0
    return dose_per_admin * frequency_per_day * duration_days
def main():
    """
    Parses command-line arguments and runs the calculator.
    """
    parser = argparse.ArgumentParser(
        description="Calculate the total dose of medication required for a treatment plan.",
        formatter_class=argparse.RawTextHelpFormatter # Allows for better help text formatting
    )
    # Add arguments for the calculator
    parser.add_argument(
        "dose", 
        type=float, 
        help="The dose per administration (e.g., 5 for 5mg)"
    )
    parser.add_argument(
        "frequency", 
        type=int, 
        help="The number of times per day the dose is given"
    )
    parser.add_argument(
        "days", 
        type=int, 
        help="The duration of the treatment in days"
    )
    # Parse the arguments provided by the user
    args = parser.parse_args()
    # Perform the calculation
    total_dose = calculate_total_medication(args.dose, args.frequency, args.days)
    # Print the result
    if total_dose > 0:
        print(f"Total medication required: {total_dose}mg")
    else:
        # argparse will have already printed an error for non-numeric types.
        # We just need to handle the positive number check.
        print("Error: All arguments must be positive numbers.")
if __name__ == "__main__":
    main()

How to Run Version 3:

You no longer run it with python largerDoses_v3.py and then type the info. You provide the arguments directly on the command line.

  1. Calculate a standard 2-week course:

    python largerDoses_v3.py 10 2 14

    Output:

    Python LargerDoses,如何高效学习Python?-图3
    (图片来源网络,侵删)
    Total medication required: 280.0mg
  2. Get help on how to use the program:

    python largerDoses_v3.py -h

    Output:

    usage: largerDoses_v3.py [-h] dose frequency days
    Calculate the total dose of medication required for a treatment plan.
    positional arguments:
      dose        The dose per administration (e.g., 5 for 5mg)
      frequency   The number of times per day the dose is given
      days        The duration of the treatment in days
    options:
      -h, --help  show this help message and exit
  3. Try with invalid input (e.g., a negative number):

    python largerDoses_v3.py 10 -2 14

    Output:

    argument frequency: -2: not a positive value

Which Version Should You Use?

  • Version 1 is great for a quick, simple script for personal use.
  • Version 2 is a significant improvement for readability, reusability, and robustness. It's an excellent example of well-structured Python code.
  • Version 3 is the most professional and is ideal if you want to create a command-line tool that can be used in scripts or by other programs.
分享:
扫描分享到社交APP
上一篇
下一篇