The input() function is a straightforward way to receive user input, making Python scripts interactive and adaptable to user-driven data. When input() is called, the program pauses and waits for the user to type something into the console. Once the user presses the Enter key, the input is read as a string (even if you entered a number). This function is particularly useful for interactive programs where user data is required.
To illustrate the input() function we will use code from other tutorials in this book to classify soils into saline, sodic, or saline-sodic soils, so that you can see how lessons in data types, functions, and control flow play together to create programs.
# ----- Request input from user -----soil_location =input("Enter location where soil was collected: ") # Manhattan, KSsoil_ec =float(input("Enter the soil EC (dS/m): ")) # EC = 5.6 dS/msoil_na =float(input("Enter the soil Na (meq/L: ")) # Na = 100 meq/Lsoil_ca =float(input("Enter the soil Ca (meq/L: ")) # Ca = 20 meq/Lsoil_mg =float(input("Enter the soil Mg (meq/L: ")) # Mg = 10 meq/L# ----- Define functions -----# Define lambda function to compute SARcalculate_sar =lambda na,ca,mg: na / ((ca+mg) /2)**0.5# Define regular function for classifying soil based on EC and SARdef classify_soil(ec,sar):if (ec >=4.0) and (sar <13): classification ="Saline"elif (ec <4.0) and (sar >=13): classification ="Sodic"elif (ec >=4.0) and (sar >=13): classification ="Saline-Sodic"else: classification ="Normal"return classification# ----- Call functions -----# Compute SAR calling lambd functionsoil_sar = calculate_sar(soil_na, soil_ca, soil_mg)# Classify soil calling regular functionsoil_class = classify_soil(soil_ec, soil_sar)# ----- Display results -----# Print soil classification including EC and SAR valuesprint(f'Soil from {soil_location} is {soil_class} (EC={soil_ec:.1f} dS/m and SAR={soil_sar:.1f})')
Enter location where soil was collected: Manhattan, KS
Enter the soil EC (dS/m): 5.6
Enter the soil Na (meq/L: 100
Enter the soil Ca (meq/L: 20
Enter the soil Mg (meq/L: 10
Soil from Manhattan, KS is Saline-Sodic (EC=5.6 dS/m and SAR=25.8)
Practice
Create a script that computes the soil bulk density, porosity, gravimetric water content, and volumetric water content given the mass of wet soil, mass of oven-dry soil, and the volume of the soil. Your code should contain a function that includes an optional input parameter for particle density with a default value of 2.65 g/cm^3.