0%

Talking with Your Program · practice

Read Decimal Numbers

int() is for whole numbers. When an answer may contain a decimal point, convert it with float().

distance_text = input("Distance in kilometers: ")
distance = float(distance_text)

If the person enters 2.5, distance_text is the "2.5" and distance is the floating-point number 2.5.

Choose the conversion that matches the value

Use int() when the program expects a whole number:

number_of_people = int(people_text)

Use float() when a fractional should be allowed:

temperature = float(temperature_text)

float() can also convert text such as "3". The result is the float 3.0.

int() cannot directly convert the string "3.5", because that string does not represent a whole integer. Python will report a rather than silently discard the decimal part.

Calculate with the converted value

Once the conversion is complete, the result behaves like any other float:

distance = float(distance_text)
double_distance = distance * 2

If distance is 2.5, double_distance becomes 5.0.

Which instruction converts the text "6.25" into a number without losing its decimal part?

Double a distance

Complete the starter program so it:

  1. converts distance_text to a float named distance;

  2. multiplies distance by 2 and stores the result in double_distance.

If the answer is 2.5, the final line should be:

Twice that distance is 5.0 kilometers.

Keep the calculation separate from the . That makes the program’s three stages easy to see: collect, convert, calculate.

Task

Convert distance_text to a float named distance. Then calculate double_distance by multiplying distance by 2.

If the input is 2.5, the final line should be:

Twice that distance is 5.0 kilometers.