Python Lesson 4
Python Lesson 4
Purpose. In the previous exercise, the user input was all text. Even if the user entered
digits 0 through nine, the computer read it as text. Even if the user intended the digit
to be a number, to the computer it was still just text. That’s the default for Python.
The purpose of this exercise is to show the difference between two types of data –
text and numbers, and how math computations can be performed with numbers.
It introduces two new functions used to convert data from text to number, float(…),
and to convert data from number to text, str(…), and introduces the practice of
creating a variable containing formatted output with “rounded off” numbers.
Float function. The word “float” used for this function is an abbreviation for “floating
point number”. The “floating point” is the decimal in numbers that have a fractional
part – like 1½ is 1.5, and the period in 1.5 is the “floating point”.
In this first example, we are using the float() function to convert the input provided by
the program user from the default text data type to a floating-point number.
Concatenating text vs. adding numbers. Remember “joining” the first and last names
in the previous assignment? “Joining” the numbers 1 and 1 in the same way would
result in 11.
Try this experiment yourself. Write some code like in the example below and run it.
Programming Exercise 4: Doing the Math [c2f]
Then edit your code to enclose the input() functions in float() functions like in the example
below. Leave everything else the same and run it.
Coding a math computation. In this exercise, your assignment is to write a program that
converts a temperature (entered from an input prompt) from Celsius to Fahrenheit. The
formula for converting temperatures on the Celsius scale to temperatures on the Fahrenheit
scale is ° F = 9/5 ( ° C) + 32.
This formula can be written as program code with very few changes. First, we create
variable names for the temperature in degrees Celsius and the temperature in
degrees Fahrenheit.
That is easy enough using the lowerCamelCase naming convention. We can just
combine the two words for each into variables names: degreesCelsius and
degreesFahrenheit.
Next, we translate the expression “9/5 ( ° C) + 32 “ into a form the computer can
interpret by using the asterisk as the multiplication operator in place of the
parentheses notation in the formula.
Substituting in the variable names for ° C and ° F, and the asterisk for the parentheses,
we get degreesFahrenheit = 9 / 5 * degreesCelsius + 32.
Order of operations. In math and computer programming, there are rules that say
which calculation comes first in evaluating an expression. They are:
• do everything inside parentheses first: ()
• then do exponents, like x2, x3 etc.
• then do multiplies and divides from left to right
• then do the adds and subtracts from left to right
So, the code for the formula above could be written in several ways without making
any difference in the result. While the form shown above suggests we could just as
well replace the 9 / 5 part with the constant 1.8, let’s change the order and preserve
all the elements in the formula by writing it this way:
degreesFahrenheit = 9 * degreesCelsius / 5 + 32
The variable degreesCelsius represents the temperature in degrees Celsius (the input),
and the variable degreesFahrenheit represents the temperature in degrees
Fahrenheit calculated from the input using the formula.
The asterisk character, *, is the operator symbol for multiplication, the forward slash
character, /, is the operator symbol for division; and the plus character, +, is the
operator symbol for addition. The formula above computes degrees on the
Fahrenheit scale by multiplying 9 times the number of degrees on the Celsius scale,
dividing that result by 5, and then adding 32.
I will introduce the str() function for converting floating-point numbers to text and a
method for “rounding off” decimal fractions later.
Remember to open up your text editor to keep a copy of your code before you start
coding in the repl.it python 3 program editor.
Your Turn.
STEP 1. DO THIS:
Copy your comment code block (first three lines) from your previous assignment
and change the exercise number to 4
Leave line 4 blank
STEP 2. DO THIS:
Remember to use the lowerCamelCase naming convention for your variable name.
Ex: degreesCelsius. Using a variable name like degreesCelsius makes it very clear
what the variable is – you could say it is self-documenting.
Write a prompt for the input statement that makes it clear what the input should
be. Ex: ‘Please enter the temperature in degrees Celsius’, or ‘What is the current
temperature in degrees Celsius?’. The prompt text is what will be displayed to the
user as an instruction or question, so the user knows what is expected as the input.
Remember you can use single quotes or double quotes to enclose your prompt.
Next, you are going to start your output code block so that you can enter a print()
function to test that your code does not have any syntax errors. This print() function
is temporary and will not be part of your final code.
STEP 3. DO THIS:
Run the program so that you can enter a number as the program user and
verify that there are no syntax errors. At this point the output should just echo
what you entered as the input.
Note that if you entered a whole number, your output will include a decimal point
and a 0 to the right of the decimal point. This indicates that the input has been
saved as a floating point number. If you forgot to enclose your input() function in a
float() function, and entered a whole number, your output would echo what you
entered exactly.
In the following steps you will be inserting new code between your current
variables code block, which contains only one line of code and your output code
block which currently contains only one print() function.
In step 4, you will create the calculations code block, enter the formula to
calculate the temperature in degrees Fahrenheit, and test that the formula is
correct.
STEP 4. DO THIS:
To test that the formula is coded correctly, enter the value 0 at the input prompt.
The output should echo the 0 that was input and then the value 32 as the
calculated value. Here is a screenshot taken after testing the code to ensure the
formula was entered correctly an produces the correct value.
This is one of three value pairs you can use to verify your formula was coded
correctly. For the other two pairs: (1) an input of 100 should produce 212 as the
calculated value, and (2) an input of -40 should produce -40 as the calculated
value.
Run the program two more times, testing with an input value of 100 and then
an input value of -40
At this point you have finished coding the algorithm that this program
implements to solve the problem of converting a temperature in the
Celsius scale to a temperature in the Fahrenheit scale; but your work as
the programmer is not done.
Now we must add code that formats the output in a way that is easy for a human
reader to understand. In the screenshot above the output is just the current values
of the two variables. Because the three input values tested were whole numbers,
and the result of the calculation in each case was a whole number, the floating
point values were displayed with the default format which includes the decimal
point and one 0 to the right of the decimal.
Now is the time to remember that you can only concatenate text strings, not
numbers. Our two temperature variables currently hold floating-point numbers. Those
numbers must be converted to text strings before they can be concatenated with
other text strings in the output variable. It’s time to introduce the str() function for this
purpose.
String function. To convert the value of a variable from number-type data to text-
type data, use the str() function.
Just like you used float() to convert the text input to a floating point number so you
could compute with it in the temperature conversion formula, you must convert the
floating point number to text before you can use it in concatenation.
Remember the plus sign is the concatenation operator to concatenate text just like
the plus sign is the addition operator to add numbers.
Enclose your variable names in the str() function as shown in the example below.
STEP 5. DO THIS:
Create a new variable named output using concatenation on line 10, right
below the calculated variable degreesFahrenheit.
Example:
output = str(degreesCelsius) + “ degrees Celsius equals “ + str(degreesFahrenheit) + “
degrees Fahrenheit.”
STEP 6. DO THIS:
If you followed all the instructions above to test your code along the way, you
should already have the output code block comment now on line 12 followed by
two print() on lines 13 and 14. It is time to replace those with a print() function that
will display the formatted contents of the output variable.
Type the output code block comment on line 12 if you don’t already have it
Edit the print() function on line 13 to include only the output variable
Delete the print() function on line 14
STEP 6. DO THIS:
Round function. You probably noticed that when you provided input to your
program in the form of whole numbers, the numbers displayed in your output
had one decimal place. But what happens if you input a number with one
decimal place? With two decimal places? Three decimal places? Four
decimal places?
If you try this you will see that generally, the displayed output has one more
decimal place than the value entered. In some cases, it will have even more
than that!
Try entering 33.3333 as your temperature input. This is what you will see
displayed as the output value: 91.99994000000001!
Not so useful.
To address this problem, we need a way to “round off” the calculated value
so it will always display with exactly the number of decimal places we want.
Fortunately, Python has a built-in round() function with two arguments we can
use, like this: round(number, number of decimal places).
STEP 7. DO THIS:
Insert a new line in the calculations code block between the calculation of the
degreesFahrenheit variable and the output variable that rounds the value of
degreesFahrenheit to one decimal place.
Run the program again to ensure there are no syntax errors and that is still works.
Try entering 33.3333 as your temperature input. Now you should see the
output value displayed as: 92.0!