5.3. Functions

5.3.1. Keyboard input, types of variables and type conversion

Copy-paste the script in the table below to your editor, save it as name2.py, and execute it. The function input reads keyboard input and assigns it to a variable (here, name).

# program for greeting people
name = input("What is your name?\n")
print("Hello, " + name + "! How are you?")

What is the difference between using + and , in a print statement? Try it!

Copy-paste the script in the table below to your editor, save it as slope.py, and execute it.

# program to enter the slope in degrees
slope = input("Enter the slope in degrees ")
print("The slope you entered is", slope, "degrees")

Add a statement that prints the type of slope. Execute the program with different inputs (e.g., 20, 35.2, 0). What is the type of the return value (here: slope) of the function raw_input?

If you want to do calculations with slope (see next section), you need slope as a floating-point value. Convert the type of slope and assign the result to a new variable by adding the line

slopeFloat = float(slope)

Add another line to the script printing the type of slopeFloat and see whether it is converted.

5.3.2. Math functions

The Universal Soil Loss Equation contains the S factor (S) representing the effect of slope steepness (s, m/m) on soil erosion. The equation is:

S = 0.065 + 0.045 s + 0.0065 s 2

Open the Python script slope.py (see previous section) and save it as s.py. Now modify it, resulting in a script that

  • asks for an input value of the slope steepness (in degrees),

  • prints the S factor.

Note that you will need type conversion, and the math module to convert from degrees to radians, and to calculate the slope as a fraction (m/m, as used in the equation) from the slope in radians (entered by the user). The Python documentation gives a list of all functions in the math module. Let the program print intermediate values of variables, in addition to the final result. Be sure to check the answer created by the script before answering the next question!


Question Run your script and enter an input value of 20 for the slope in degrees. What is S?

  1. 0.032

  2. 0.82

  3. 0.082

  4. 0.32