\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% Differential \newcommand\dd[2][]{\mathrm{d}^{#1}{#2}} % use as \dd, \dd{x}, or \dd[2]{x}\\% Poor man's siunitx \newcommand\unit[1]{\mathrm{#1}} \newcommand\num[1]{#1} \newcommand\qty[2]{#1~\unit{#2}}\\\newcommand\per{/} \newcommand\squared{{}^2} \newcommand\cubed{{}^3} % % Scale \newcommand\milli{\unit{m}} \newcommand\centi{\unit{c}} \newcommand\kilo{\unit{k}} \newcommand\mega{\unit{M}} % % Percent \newcommand\percent{\unit{{\kern-4mu}\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{\kern-4mu}^\circ}} % % Time \newcommand\second{\unit{s}} \newcommand\s{\second} \newcommand\minute{\unit{min}} \newcommand\hour{\unit{h}} % % Distance \newcommand\meter{\unit{m}} \newcommand\m{\meter} \newcommand\inch{\unit{in}} \newcommand\foot{\unit{ft}} % % Force \newcommand\newton{\unit{N}} \newcommand\kip{\unit{kip}} % kilopound in "freedom" units - edit made by Sri % % Mass \newcommand\gram{\unit{g}} \newcommand\g{\gram} \newcommand\kilogram{\unit{kg}} \newcommand\kg{\kilogram} \newcommand\grain{\unit{grain}} \newcommand\ounce{\unit{oz}} % % Temperature \newcommand\kelvin{\unit{K}} \newcommand\K{\kelvin} \newcommand\celsius{\unit{{}^\circ C}} \newcommand\C{\celsius} \newcommand\fahrenheit{\unit{{}^\circ F}} \newcommand\F{\fahrenheit} % % Area \newcommand\sqft{\unit{sq\,\foot}} % square foot % % Volume \newcommand\liter{\unit{L}} \newcommand\gallon{\unit{gal}} % % Frequency \newcommand\hertz{\unit{Hz}} \newcommand\rpm{\unit{rpm}} % % Voltage \newcommand\volt{\unit{V}} \newcommand\V{\volt} \newcommand\millivolt{\milli\volt} \newcommand\mV{\milli\volt} \newcommand\kilovolt{\kilo\volt} \newcommand\kV{\kilo\volt} % % Current \newcommand\ampere{\unit{A}} \newcommand\A{\ampere} \newcommand\milliampereA{\milli\ampere} \newcommand\mA{\milli\ampere} \newcommand\kiloampereA{\kilo\ampere} \newcommand\kA{\kilo\ampere} % % Resistance \newcommand\ohm{\Omega} \newcommand\milliohm{\milli\ohm} \newcommand\kiloohm{\kilo\ohm} % correct SI spelling \newcommand\kilohm{\kilo\ohm} % "American" spelling used in siunitx \newcommand\megaohm{\mega\ohm} % correct SI spelling \newcommand\megohm{\mega\ohm} % "American" spelling used in siunitx % % Capacitance \newcommand\farad{\unit{F}} \newcommand\F{\farad} \newcommand\microfarad{\micro\farad} \newcommand\muF{\micro\farad} % % Inductance \newcommand\henry{\unit{H}} \newcommand\H{\henry} \newcommand\millihenry{\milli\henry} \newcommand\mH{\milli\henry} % % Power \newcommand\watt{\unit{W}} \newcommand\W{\watt} \newcommand\milliwatt{\milli\watt} \newcommand\mW{\milli\watt} \newcommand\kilowatt{\kilo\watt} \newcommand\kW{\kilo\watt} % % Energy \newcommand\joule{\unit{J}} \newcommand\J{\joule} % % Composite units % % Torque \newcommand\ozin{\unit{\ounce}\,\unit{in}} \newcommand\newtonmeter{\unit{\newton\,\meter}} % % Pressure \newcommand\psf{\unit{psf}} % pounds per square foot \newcommand\pcf{\unit{pcf}} % pounds per cubic foot \newcommand\pascal{\unit{Pa}} \newcommand\Pa{\pascal} \newcommand\ksi{\unit{ksi}} % kilopound per square inch % NOTE: do NOT define \bar -- it is the built-in LaTeX accent used by \bar{x}, % \bar{y} (sample means). Redefining it made those render as the word "bar". \newcommand\barunit{\unit{bar}} \end{aligned}\end{align} \]

Nov 16, 2026 | 1528 words | 15 min read

9.3.1. PY: Logic and Modularity#

You are a junior engineer supporting two projects. A local farmer needs help determining whether an irrigation system is watering correctly, while a mission team needs to calculate the escape velocity required to leave a planet. You will develop one menu-driven Python program containing both engineering tools, analyze the organization and design of the program, and create a flowchart representing its program flow.

Required Files#

  1. Download the Python template ENGR131_Python_Template.py and save it as 9_3_1_username.py.

  2. Download the report template, complete it, and save it as 9_3_1_report_username.pdf.

  3. Create and save your program flowchart as a PDF or a PNG: 9_3_1_flowchart_username.pdf or 9_3_1_flowchart_username.png.

Quick Guide: Completing & Submitting Your Report as PDF

To complete your technical report, you must edit the provided Word template (.docx) and convert it to a PDF for final grading. Follow this simplified workflow:

  1. Edit in Word: Download and open the .docx template in Microsoft Word. Avoid editing in web previewers or Google Docs, as they will corrupt your formulas and chart formatting.

  2. Save as PDF Only When Finished: Type your answers and copy any charts or images directly into the Word document, saving your progress frequently. Once your report is 100% complete, save or export the document as a PDF. (Do not convert to PDF early, as PDFs are static and cannot be edited!) Copy charts or images into the report and keep the originals in the workbook, since Gradescope grades the workbook.

  3. Submit to Gradescope: Upload your finalized PDF and any other required deliverables to the corresponding assignment in Gradescope. Always review your uploaded files from the Gradescope confirmation screen to verify your work is complete.

Reminder

Rename your files with your Purdue username, replacing “template” in the filename. Then fill out any required information in the template such as student name, email, etc.

Task 1: A Field Engineer’s Toolkit#

Rather than developing two separate scripts, your supervisor has asked you to create a single command-line toolkit. When the program runs, it will present the user with a menu and route the user to the appropriate engineering tool based on their selection. The irrigation system check will use conditional logic to evaluate operating conditions, while the escape velocity calculator will use a sequence of engineering calculations to determine the required velocity.

Organize the program using user-defined functions so that each function performs a specific task. This modular structure will make the program easier to read, test, debug, and reuse.

Reminder

Review and reference the Python Style Guide to ensure your code follows the required formatting and documentation standards, including the use of clear and descriptive comments.

Main Function: Menu and Program Routing#

Create a main function that displays the menu, collects the user’s selection, and calls the appropriate user-defined function.

When the program runs, it should prompt the user with:

Select a tool:
  1) Irrigation System Check
  2) Escape Velocity Calculator
Enter choice (1 or 2):

Use an if-elif-else structure to route the program:

  • If the user enters 1, call the user-defined function for the irrigation system check.

  • If the user enters 2, call the user-defined function for the escape velocity calculator.

  • If the user enters any other value, display an appropriate warning message and call main() again to redisplay the menu.

The main function should manage the overall program flow. Place the detailed calculations and decision-making logic within the appropriate user-defined functions.

Irrigation System Check#

Create a user-defined function that collects information about the irrigation system, validates the inputs, and displays an operating recommendation.

User Input#

Prompt the user to enter:

  • soil moisture as a percentage from 0 to 60,

  • forecasted rain in millimeters from 0 to 50,

  • whether the system is experiencing low pressure, and

  • whether the system requires maintenance.

Use the following prompts:

Enter soil moisture (%, 0-60):
Enter forecasted rain (mm, 0-50):
Is the system experiencing low pressure? (yes/no):
Is maintenance needed? (yes/no):

Convert the soil moisture and forecasted rain inputs to float values. Format the two yes/no responses using the appropriate string methods so that differences in capitalization or extra spaces do not affect the program.

Input Validation#

Validate the inputs before evaluating the irrigation conditions.

  • If either numeric input is outside its expected range, display a warning message and use return to end the function early.

  • Convert each valid yes/no response to a Boolean value. Assign True when the response is yes and False when the response is no. If the user enters any other response, display a warning and assign False.

Irrigation Recommendation#

Evaluate the conditions in the order shown below. Once a condition is satisfied, display the corresponding recommendation.

Priority

Condition

Recommendation

1

Maintenance is required

DO NOT IRRIGATE - maintenance required.

2

The system is experiencing low pressure

DO NOT IRRIGATE - low pressure condition.

3

Forecasted rain is at least 10 mm

DELAY - significant rainfall expected.

4

Soil moisture is less than 20%

RUN FULL

5

Soil moisture is between 20% and 25%, inclusive

RUN REDUCED

6

Soil moisture is greater than 25%

SKIP - soil moisture is adequate.

Escape Velocity Calculator#

Create a user-defined function that prompts the user for information about a planet and calculates its escape velocity. Organize the calculations into separate user-defined functions.

User Input#

Prompt the user to enter:

  • the planet’s average density in \(\kilogram/\meter^3\), and

  • the planet’s radius in \(\meter\).

Use the following prompts:

Enter the density of the planet (kg/m^3):
Enter the radius of the planet (m):

Convert both inputs to float values.

Calculations#

Create separate user-defined functions for each calculation. Choose clear, descriptive names for the functions and their parameters.

Table 9.5 Escape Velocity Calculation Functions#

Function Purpose

Parameters

Calculation

Returned Value

Calculate planet volume

Radius

\(V = \frac{4}{3}\pi r^3\)

Planet volume

Calculate planet mass

Density and volume

\(m = \rho V\)

Planet mass

Calculate escape velocity

Mass and radius

\(v_e = \sqrt{\frac{2Gm}{r}}\)

Escape velocity

In these equations:

  • \(r\) is the planet’s radius in meters,

  • \(\rho\) is the planet’s average density in \(\mathrm{kg/m^3}\),

  • \(V\) is the planet’s volume in \(\mathrm{m^3}\),

  • \(m\) is the planet’s mass in kilograms, and

  • \(G\) is the gravitational constant, \(6.6743 \times 10^{-11}\).

Import the math module. Use math.pi for \(\pi\) and math.sqrt() to calculate the square root. Each function must return its calculated value. Convert the radius from meters to kilometers before displaying the results. This can be done using division in Python.

The example flowchart below demonstrates how the escape velocity calculation can be divided among multiple user-defined functions. Each function performs one calculation and returns its result for use in the next calculation.

Flowchart for an escape velocity calculator using modular functions.

Fig. 9.1 Example organization of the escape velocity calculations using user-defined functions.#

Program Output#

Your final program output must:

  • display the menu and all required input prompts,

  • display the appropriate irrigation recommendation when the irrigation system check is selected,

  • display the planet’s radius in kilometers when the escape velocity calculator is selected,

  • display the escape velocity in meters per second,

  • format the radius and escape velocity to two decimal places, and

  • use clear labels and spacing for readability.

Use the sample output below to verify that your program produces the expected values and follows the required output format.

The meaning of each test input depends on the selected tool:

Table 9.6 Test Input Key#

Menu Choice

Tool

Input 1

Input 2

Input 3

Input 4

1

Irrigation System Check

Soil moisture (%)

Forecasted rain (mm)

Low pressure

Maintenance required

2

Escape Velocity Calculator

Density (\(\kilogram/\meter^3\))

Radius (\(\meter\))

Not used

Not used

Sample Output#

Use the values in Table 9.7 below to test your program.

Table 9.7 Test Cases#

Case

Menu choice

Input 1

Input 2

Input 3

Input 4

1

1

15

0

no

yes

2

1

5

23

yes

no

3

1

15

23

no

no

4

1

15

0

no

no

5

2

5513.0

6371000

6

2

1879.8

2574730

Ensure your program’s output matches the provided samples exactly. This includes all characters, white space, and punctuation. In the samples, user input is highlighted like this for clarity, but your program should not highlight user input in this way.

Case 1 Sample Output

$ python3 9_3_1_username.pySelect a tool: 1) Irrigation System Check 2) Escape Velocity CalculatorEnter choice (1 or 2): 1Enter soil moisture (%, 0-60): 15Enter forecasted rain (mm, 0-50): 0Is the system experiencing low pressure? (yes/no): noIs maintenance needed? (yes/no): yesDO NOT IRRIGATE - maintenance required.

Case 2 Sample Output

$ python3 9_3_1_username.pySelect a tool: 1) Irrigation System Check 2) Escape Velocity CalculatorEnter choice (1 or 2): 1Enter soil moisture (%, 0-60): 5Enter forecasted rain (mm, 0-50): 23Is the system experiencing low pressure? (yes/no): yesIs maintenance needed? (yes/no): noDO NOT IRRIGATE - low pressure condition.

Case 3 Sample Output

$ python3 9_3_1_username.pySelect a tool: 1) Irrigation System Check 2) Escape Velocity CalculatorEnter choice (1 or 2): 1Enter soil moisture (%, 0-60): 15Enter forecasted rain (mm, 0-50): 23Is the system experiencing low pressure? (yes/no): noIs maintenance needed? (yes/no): noDELAY - significant rainfall expected.

Case 4 Sample Output

$ python3 9_3_1_username.pySelect a tool: 1) Irrigation System Check 2) Escape Velocity CalculatorEnter choice (1 or 2): 1Enter soil moisture (%, 0-60): 15Enter forecasted rain (mm, 0-50): 0Is the system experiencing low pressure? (yes/no): noIs maintenance needed? (yes/no): noRUN FULL

Case 5 Sample Output

$ python3 9_3_1_username.pySelect a tool: 1) Irrigation System Check 2) Escape Velocity CalculatorEnter choice (1 or 2): 2Enter the density of the planet (kg/m^3): 5513.0Enter the radius of the planet (m): 6371000---Calculator Results---Planet radius: 6371.00 kmEscape velocity: 11185.72 m/s

Case 6 Sample Output

$ python3 9_3_1_username.pySelect a tool: 1) Irrigation System Check 2) Escape Velocity CalculatorEnter choice (1 or 2): 2Enter the density of the planet (kg/m^3): 1879.8Enter the radius of the planet (m): 2574730---Calculator Results---Planet radius: 2574.73 kmEscape velocity: 2639.67 m/s

Task 2: Program Analysis and Flowchart#

After completing and testing your Python program, analyze its organization and create a flowchart representing the complete program flow.

Program Analysis#

Complete the analysis questions in the report template downloaded from the Required Files section. Use specific examples from your program to support your responses and use clear, professional language.

Save the completed report as 9_3_1_report_username.pdf.

Program Flowchart#

Create a flowchart representing the complete program. The flowchart must include:

  • the menu and initial user selection,

  • the program path for each menu option,

  • the major validation and decision paths used by the irrigation system check,

  • each user-defined function call used by the escape velocity calculator, and

  • the values returned by the calculation functions.

We recommend using diagrams.net to create the flowchart.

Export the completed flowchart as a PDF or PNG using the flowchart filename specified in the Required Files section.

Gradescope Submission#

  1. Save Deliverables: Ensure all required assignment files are saved and named exactly as specified in the assignment instructions. If a template file name contains the word template, replace only that word with your Purdue username. When a task lists more than one deliverable, such as a workbook and a report, submit each deliverable to its own matching Gradescope assignment instead of combining them into one upload.

  2. Navigate to Gradescope: Log in to Gradescope. From your Dashboard, open the assignment.

  3. Upload your work: Select the Upload submission method. Drag and drop all required files (or a compressed .zip folder) into Gradescope, and select Upload.

  4. Confirm Submission: When your upload is successful, you will see a confirmation message on your screen and receive an automated email receipt.

  5. Add Team Members (if applicable): If this is a team assignment, add all team members to the submission. Each teammate should confirm they can see the submission in their own Gradescope account. For help, visit Gradescope’s documentation on adding team members.

  6. Review Autograder Results: Wait a few minutes for the autograder to evaluate the relevant files. Scroll down to view any failed test cases. If you need assistance interpreting the output or errors, ask your teaching team.

  7. Resubmit if Necessary: You can edit your files and select Resubmit as many times as you need before the assignment deadline. Only your final, active submission is graded. (Note: If you need to resubmit, you must upload all required files for the assignment again).

For a detailed walkthrough, review the official Gradescope Submission Guide.