DoAssignment study guide

A1.2 · Convert data types explicitly and safely

Learn to convert data types explicitly and safely through clear examples and targeted practice.

Ontario Grade 12 Computer Science

Programming Concepts and Skills

ICS4U A1.2 — Make conversions deliberate and check that they are appropriate

A program treats text, whole numbers, decimal numbers and true-or-false values differently. For example, adding two numbers finds a total, while joining two pieces of text makes a longer string. When information arrives in a different type from the one an operation needs, convert it deliberately. In this lesson, “safe” means that the program has a suitable input expectation, checks whether conversion is possible, and avoids silently changing the meaning of a value. Python 3 is used for examples; other classroom languages may express conversions differently.

What you will learn

  • Explain why a value’s data type matters when a program uses it.
  • Choose an explicit conversion that matches the intended use of a value.
  • Check user-provided text before relying on a conversion, and handle invalid input safely.
  • Recognize conversions that can lose information or produce an unintended result.

1. Review: values have types

A variable refers to a value, and that value has a type. In Python 3, common types include `str` for text, `int` for whole numbers, `float` for numbers that can include a decimal part, and `bool` for `True` or `False`. The characters `42` entered at a prompt are text, even if they look like a number.
The type affects what an operation means. If `first` and `second` are both strings, `first + second` joins their text. If they are both integers, `first + second` adds their values. A program should not rely on a reader or the computer to guess which meaning was intended.
An explicit conversion names the intended change, such as `int(text)` or `str(number)`. But naming a conversion does not guarantee that every possible input is acceptable. Converting text such as `"many"` to an integer raises an error. A safe program considers what inputs are allowed and what it will do if the input cannot be converted.
  • Prompt input is text unless the program converts it.
  • Choose a target type based on the operation and the meaning of the data.
  • A conversion can fail or discard information.

2. A safe conversion process

Use a simple sequence. First, identify the type you have and the type you need. Next, state a reasonable precondition: for example, the input should represent a whole number. Then perform the explicit conversion. Finally, use the result only if conversion succeeded; otherwise, show a clear message or request a different value.
In Python 3, a `try` and `except ValueError` can handle text that cannot be converted by `int` or `float`. Put the conversion in the `try` block and the response to invalid text in the `except` block. This makes the failure path part of the program rather than leaving it as an unexpected crash.
Not every conversion that succeeds is suitable. Converting a decimal number to an integer drops the fractional part; it does not round to the nearest whole number. Also, `bool("False")` is `True` in Python because a non-empty string is treated as true. If text is meant to represent a yes-or-no answer, compare it with the allowed words instead of relying on `bool` conversion.
For each conversion, ask: What type is the input? What type does the next operation require? Which inputs are acceptable? Could the conversion lose meaningful information? What should happen when the input is not acceptable?
  • State acceptable input before converting.
  • Handle a conversion error with a planned response.
  • Check whether the conversion preserves the meaning the program needs.

3. Short Python 3 patterns

These examples are for reading and tracing; they are not claims that code was run. In the first pattern, the precondition is that the program receives text that may or may not represent an integer. The input is one line of text. The algorithm attempts an explicit conversion, then either displays the converted integer or reports that the input was unsuitable.
In the second pattern, the program needs to interpret text as a yes-or-no response. It removes surrounding spaces and changes letters to lowercase before comparing against the accepted responses. The precondition is that only `yes` and `no`, ignoring case and surrounding spaces, are accepted. Any other text receives an invalid-response message.
These patterns make the expected output depend on the input. They do not silently treat arbitrary text as a valid number or answer. When a program asks again after invalid input, that repetition should also be made explicit; the examples below instead report the problem and finish that attempt.
  • Use `try` and `except ValueError` for conversions that may reject text.
  • For text choices, compare with documented accepted values.
  • A clear invalid-input response is part of safe conversion.

4. Practice and review

Before converting a value in your own program, write down its current type, the needed type, the accepted input and the result if conversion is not possible. Then trace one acceptable input and one unacceptable input by following the code in order. This small check often reveals a missing error response or an unintended type.
Practice: A prompt collects the text `"18"`, and the program needs a whole-number quantity. Identify the explicit conversion and state what should happen if the user enters `"eighteen"`. Next, consider a prompt that accepts only `yes` or `no`: explain why converting the response with `bool` would not correctly interpret the word `no`.
A suitable answer identifies `int` as the target type for the quantity, handles a failed conversion with a message or another attempt, and checks yes-or-no text against the accepted words. The quick check below tests these same decisions.
  • Trace both valid and invalid examples.
  • Do not confuse a conversion that runs with one that preserves the intended meaning.
  • Plan what the program communicates when input is rejected.

Worked example

Convert text to a whole number

A program receives a line of text for a number of tickets. It should display the integer when the text represents one and give a message otherwise. What conversion and handling are appropriate?

Python 3

text = input("Ticket count: ")
try:
    count = int(text)
    print("Tickets:", count)
except ValueError:
    print("Enter a whole number.")
  1. Set the input expectation
    The input is text. The intended result is a whole-number ticket count, so attempt conversion with `int`. Because the input may not represent an integer, include a response to `ValueError`.
  2. Trace an acceptable value
    For input `"27"`, `int` produces the integer value 27. The program follows the success path and displays `Tickets: 27`.
  3. Trace an unacceptable value
    For input `"twenty"`, `int` cannot produce an integer and raises `ValueError`. The exception handler displays `Enter a whole number.` rather than continuing as if conversion had succeeded.
Answer: Use an explicit `int` conversion inside a `try` block, and handle `ValueError` with a clear message.
Check: The program has a defined response for text that cannot be converted. Whether a negative count should be accepted is a separate input rule that would need to be stated and checked.

Worked example

Interpret a yes-or-no response

A program receives a text response and should display `Confirmed` only for yes, `Not confirmed` for no, and an error message for any other text. How can it convert the response safely?

Python 3

answer = input("Confirm? ").strip().lower()
if answer == "yes":
    print("Confirmed")
elif answer == "no":
    print("Not confirmed")
else:
    print("Enter yes or no.")
  1. Define accepted input
    The accepted responses are the words yes and no, allowing different letter cases and surrounding spaces. The program should not treat every non-empty string as a true answer.
  2. Normalize and compare
    For input `" YES "`, `strip` removes the surrounding spaces and `lower` changes the letters to lowercase. The resulting text is `yes`, so the program displays `Confirmed`.
  3. Handle other text
    For input `"maybe"`, neither accepted comparison matches. The final branch displays `Enter yes or no.`. This gives unexpected input an explicit outcome.
Answer: Normalize the text, compare it with the accepted words, and handle all other responses separately.
Check: A direct `bool` conversion is unsuitable here: any non-empty string, including `"no"`, is true in Python.

Worked example

Avoid losing a decimal part

A program receives the text `"6.5"` for a measurement that may include a decimal part. It must preserve that part. Which conversion is appropriate, and why is `int` unsuitable?

Python 3

text = input("Measurement: ")
try:
    measurement = float(text)
    print("Measurement:", measurement)
except ValueError:
    print("Enter a number.")
  1. Choose the needed type
    Since the measurement can include a fractional part, use `float` rather than `int`. The input is text; the intended result is a decimal number.
  2. Trace the conversion
    For input `"6.5"`, `float` produces the numeric value 6.5, which the program can display as `Measurement: 6.5`.
  3. Compare the unsuitable choice
    Using `int` on `"6.5"` raises `ValueError`; it does not accept decimal-point text as an integer. If a program first converted to `float` and then to `int`, it would discard the fractional part. That would not preserve this measurement.
Answer: Convert the text to `float` and handle `ValueError`. Do not convert the measurement to `int` when its fractional part matters.
Check: The precondition is that acceptable input represents a decimal number. Invalid text still needs a planned response.

Common mistakes and how to avoid them

Assuming text that looks numeric is already a number.
Correction: Prompt input is text. Convert it explicitly before using it as a number, and handle input that cannot be converted.
Using `int` on a decimal measurement because the program needs a number.
Correction: Choose `float` when the fractional part matters. Converting a decimal value to an integer can discard that part.
Using `bool(response)` to interpret the words yes and no.
Correction: Compare normalized text with the accepted words. A non-empty string such as `"no"` is true when converted with `bool`.
Treating a successful conversion as proof that the value is appropriate for every purpose.
Correction: Check both whether conversion is possible and whether the converted value preserves the meaning needed by the program.

Lesson summary

  • Identify the current type and the type required for the next operation.
  • Use an explicit conversion that matches the data’s intended meaning.
  • State acceptable input and handle conversion failure deliberately.
  • Check for information loss and avoid misleading conversions such as using `bool` on yes-or-no text.

Check your understanding

Question 1

A prompt returns the text `"31"`, and the program needs a whole-number value. Which conversion is appropriate?
  1. `int(text)`, with a response planned for invalid input
  2. `bool(text)`, because the text contains a number
  3. `str(text)`, because prompt input is text
  4. `float(text)` in every case, even when a whole-number value is required
Show answer and explanation
`int(text)`, with a response planned for invalid input
`int` produces a whole-number value from suitable text. Input that is not a valid integer should be handled rather than assumed to convert.

Question 2

In Python 3, what is the result of converting the non-empty string `"no"` with `bool`?
  1. `False`, because the word means no
  2. `True`, because the string is non-empty
  3. An integer value
  4. A conversion error
Show answer and explanation
`True`, because the string is non-empty
Python treats a non-empty string as true. To interpret yes-or-no words, compare the text with the accepted responses.

Question 3

A measurement is entered as `"4.8"`, and its decimal part matters. Which approach best preserves its intended meaning?
  1. Convert it to `int` and use the whole-number result
  2. Convert it to `bool`
  3. Convert it to `float` and handle invalid text
  4. Leave it as text and add it to other numeric measurements
Show answer and explanation
Convert it to `float` and handle invalid text
`float` can represent the decimal value. An integer conversion is unsuitable when the fractional part must be preserved.

Key terms

Data type
A category that determines what kind of value is stored and how operations use it, such as text, integer, decimal number or Boolean.
Explicit conversion
A deliberate instruction that changes a value to a named type, such as converting suitable text with `int`.
Precondition
A condition that should be true for an operation or program step to be used as intended, such as input representing an integer.
Boolean
A true-or-false value, written in Python 3 as `True` or `False`.
ValueError
A Python error raised when a value is unsuitable for the requested operation, such as text that cannot be converted to an integer.

Continue through ICS4U

View the complete ICS4U Ontario Grade 12 Computer Science curriculum and lessons

About this lesson and its review

Published by DoAssignment. This reviewed lesson follows Ontario Grade 12 Computer Science (ICS4U), expectation A1.2. It is a study resource, not an official curriculum publication.

Before publication, content is checked for structure, mathematical or chemical notation, calculations, course boundaries, and readability. Errors can still occur, so corrections are welcomed.

Official curriculum reference

Report a correction or ask a question