Recommended resources
The freely available resources this lesson will direct you to.
Hello! In the last lesson, you calculated a distance and stored a Boolean check called within_range. That check could tell you whether a value was acceptable, but it did not change what the program did. Today you’ll read values from the console, make text input more consistent, and use if, elif, and else to choose a response. These skills will let your command-line unit converter respond to the person using it rather than relying on values written into the file.
Allow about 40–45 minutes to read, watch, and run the examples. In your existing VS Code project, create input_and_choices.py. Save it with Command–S before each run, and use Run Python File so you can type responses in the terminal.
Console input arrives as text
The input() function displays a prompt and pauses the program until you type a response and press Return. It then gives your program that response as a string.
Basic Input and Output in Python
Read Real Python’s explanation of keyboard input to see why a number typed at the console is not yet a number your program can calculate with.
In “Reading Input From the Keyboard,” read input and conversion, stopping at the note about invalid numeric input, just before “Writing Output to the Console.” Focus on the type(number) example, the failed attempt to add 100, and how int() changes the result.
Try this in input_and_choices.py:
distance_text = input("Distance in metres: ")
print("You entered:", distance_text)
print("Python stored a:", type(distance_text))
If you type 2.5, the displayed type is <class 'str'>. The characters look like a decimal number, but input() always returns text. As you saw last time, text and numbers behave differently under operators. To calculate with this response, convert it with float():
distance_text = input("Distance in metres: ")
distance_m = float(distance_text)
distance_mm = distance_m * 1000
print("Converted distance:", distance_mm, "mm")
Typing 2.5 now produces 2500.0 mm. We use float() rather than int() because a measurement can contain a decimal part. Conversion is not automatic: it is an explicit step between reading text and doing arithmetic.
There is a limit to this version. If you enter two or press Return without entering anything, float() cannot convert the response and raises a ValueError. We’ll guard against an empty response in this lesson; handling arbitrary invalid numeric text without a crash comes later when you study exceptions.
Normalize text before comparing it
People may enter MM, mm, or mm to mean the same unit. Normalization turns predictable variations into one form before your program makes a decision.
unit = input("Convert to mm or cm? ").strip().lower()
print("Normalized choice:", unit)
Here, .strip() removes whitespace at the beginning and end of the response. Then .lower() changes uppercase letters to lowercase. Typing MM therefore leaves unit holding "mm". These operations do not remove spaces inside a response: "m m" remains "m m", which is not a supported unit.
The same idea helps with blank input. After .strip(), a response made only of spaces becomes the empty string "". That gives your program a clear value to check instead of treating several spaces as a measurement.
Notice that normalization depends on what the input means. Lowercasing a unit choice is useful because capitalization does not change the unit. For a numeric measurement, stripping surrounding spaces is useful, but lowercasing has no purpose:
distance_text = input("Distance in metres: ").strip()
At this point, distance_text is still a string. Normalizing text and converting it to a number are separate operations.
Turn a check into a decision
Watch how a conditional runs one block of code and skips another. The video uses a rating as its example; in your program, the deciding value will be a unit choice or measurement.
Using Conditionals (If, Elif, Else) in Python | Learning Python for Beginners | Code with Kylie #4
Watch Kylie Ying’s “Using Conditionals (If, Elif, Else) in Python” for a visual explanation of branches and an example that eventually takes numeric input.
Watch the first condition for what runs when a check is true and why indentation matters. Continue with the alternative to see else, then additional branches to see elif. Finish with user input, focusing on why the response is converted to float() before a numeric comparison.
An if statement tests a condition. Its indented block runs only when that condition is True:
distance_m = 2.5
if distance_m <= 3.0:
print("Distance is within the 3 m limit.")
print("Check complete.")
Both lines print for 2.5. Change the value to 3.5: the indented message is skipped, but Check complete. still prints. The colon begins the conditional block; the four spaces of indentation show which statement belongs to it. When you return to the left margin, you have left the block.
Use else when you want a different response if the condition is false:
if distance_m <= 3.0:
print("Distance is within the 3 m limit.")
else:
print("Distance exceeds the 3 m limit.")
Exactly one of these two messages prints. else needs a colon but no condition: it means “otherwise.” If there are more than two possible outcomes, add elif—short for “else if”:
if distance_m < 0:
print("Distance cannot be negative.")
elif distance_m <= 3.0:
print("Distance is within the 3 m limit.")
else:
print("Distance exceeds the 3 m limit.")
Python checks these branches in order and runs the first one whose condition is true. For -1, it prints the negative-distance message and does not reach the other branches. For 3.0, the first condition is false and the second is true, so the distance is within the limit. For 3.5, neither condition is true, so else runs.
Branch order matters. If you checked distance_m <= 3.0 first, a negative measurement would satisfy that condition and be reported as within the limit. Also recall the distinction from last lesson: = assigns a value; == tests whether two values are equal.
Put input and decisions together
Now replace the file contents with a small, interactive converter. It accepts metres in the range 0 to 3 and lets the user choose centimetres or millimetres.
unit = input("Convert to mm or cm? ").strip().lower()
distance_text = input("Distance in metres (0 to 3): ").strip()
if unit != "mm" and unit != "cm":
print("Choose mm or cm.")
elif distance_text == "":
print("Enter a distance.")
else:
distance_m = float(distance_text)
if distance_m < 0 or distance_m > 3:
print("Distance must be between 0 and 3 m.")
elif unit == "mm":
print("Converted distance:", distance_m * 1000, "mm")
else:
print("Converted distance:", distance_m * 100, "cm")
Read the code from top to bottom. It first collects and normalizes both responses. The outer branches check whether the unit is supported and whether a measurement was supplied. Only after those checks does the program call float(). Inside that else block, a second conditional checks the numeric range and chooses the conversion. The extra indentation shows that this second decision happens only after the earlier checks have passed.
The condition unit != "mm" and unit != "cm" means the choice matches neither supported unit. The range check uses or: a measurement is unacceptable if it is below 0 or above 3. In each case, the operators are producing the Boolean result that selects a branch.
Run the file separately with these responses to see the branches in action:
| Unit entered | Distance entered | Expected response |
|---|---|---|
MM |
2.5 |
Converted distance: 2500.0 mm |
cm |
3 |
Converted distance: 300.0 cm |
mm |
spaces only | Enter a distance. |
miles |
2 |
Choose mm or cm. |
cm |
-1 |
Distance must be between 0 and 3 m. |
One important boundary remains: cm followed by three still causes a ValueError. The blank-input check catches an empty string, not every string that fails numeric conversion. Rather than silently pretending invalid text is zero, the program leaves that case for proper exception handling later in the course.
Where this leaves your converter
You can now collect console input, remember that it starts as a string, normalize predictable text variations, convert numeric text when appropriate, and choose behavior with if, elif, and else. You have also seen why branch order, colons, and consistent indentation affect what the program does.
Keep input_and_choices.py: it is an early version of your Week 1 converter. Next, you’ll use loops to repeat an operation instead of running the program again for every conversion.