Every beginner writes this line sooner or later: age = input("Enter your age: "), followed by a calculation, followed by a confusing error or a result that makes no sense, like “adding” 5 to 10 and getting 105. The culprit is one simple fact: input() always returns a string, even when the user types digits. This guide shows you how to convert input into integers and floats properly, how to handle the mistakes users inevitably type, and how to build a reusable helper that asks for a number and never crashes.
Quick Answer
Wrap the input in a conversion: age = int(input("Enter your age: ")) for whole numbers, or price = float(input("Enter the price: ")) for decimals. Because users type invalid text, protect the conversion with a try/except ValueError inside a loop that asks again until the input is valid. Never do maths on the raw result of input(), because it is text, and text behaves differently.
Why input() Gives You a String
Python cannot know in advance what you plan to do with the typed text, so input() returns exactly what the user typed, as a string. That design has visible consequences. Adding two raw inputs concatenates them: inputs of 10 and 5 produce "105", not 15. Multiplying a string by a number repeats it: "5" * 3 gives "555". Comparing strings is alphabetical, so "9" > "10" is even True. Every one of these surprises disappears the moment you convert to a number first. The official input() documentation states the string behaviour plainly.
Choosing int or float
- Use
int()for whole numbers only: ages, counts, quantities, menu choices. It rejects any text with a decimal point or letters. - Use
float()for anything that might contain a fraction: prices, weights, measurements, averages.float()also accepts whole numbers, returning values like42.0, so it is the safer default when you are unsure. - Convert float back when needed:
int(float(text))accepts"3.9"and gives3, dropping the fraction. If you want rounding instead of dropping, useround(float(text)).
The Pattern That Never Crashes
One bare conversion line works only until the first typo. The professional pattern is a small loop that keeps asking until the answer converts cleanly:
def ask_int(prompt):
while True:
text = input(prompt)
try:
return int(text)
except ValueError:
print("Please type a whole number.")
Then your program simply says age = ask_int("Enter your age: "). Write the float version the same way with float(text). Once this helper exists, every input in the program becomes one tidy line, and no typo can kill the program. If you have already met the crash this prevents, our guide to the invalid literal for int() ValueError explains that error message itself in depth.
Validating Beyond “Is It a Number”
A valid number can still be a wrong answer. An age of -50 or 9000 converts perfectly. Add a range check inside the loop: after converting, test if 0 <= age <= 120: and return the value only then, otherwise print a specific message and loop again. The same approach guards menu choices (only 1 to 4 allowed), percentages (0 to 100), and quantities (at least 1). Conversion answers “is it numeric”; validation answers “is it sensible”, and good input handling does both.
Reading Several Numbers at Once
When a program needs a list of numbers, let the user type them separated by spaces or commas and split the text: parts = input("Enter scores: ").split() gives a list of strings. Convert each with a loop or a comprehension: scores = [int(p) for p in parts]. Wrap the comprehension in try/except so one bad token asks for the whole line again. This style keeps console programs fast to use and easy to test, because you can paste a whole row of sample data in one go.
Common Mistakes to Avoid
- Doing maths on the raw string. The
"10" + "5" = "105"concatenation trap is the most common beginner bug in Python. Convert first, always. - Converting with int() when decimals are possible. One user typing
2.5will crash the program. If fractions make sense for the value, convert withfloat(). - Trusting a single attempt. Without a retry loop, the first invalid keystroke ends the program and loses the user’s other answers.
- Forgetting the variable changes type. After conversion, the variable holds a number. If later code needs to display it inside a sentence, f-strings handle the conversion back to text automatically.
Printing Numbers Back Nicely
Once input is a real number, displaying results well is the other half of the job, and f-strings do the heavy lifting. Placing a variable inside an f-string inserts its text form automatically, so f"Your age is {age}" needs no manual conversion. Format specifications after a colon polish the output: {price:.2f} always shows two decimal places, which money demands; {total:,} adds thousands separators, turning 1000000 into 1,000,000; and {score:.0%} renders a fraction like 0.85 as 85%. These touches make a beginner program feel finished, and they only work cleanly because the values are genuine numbers rather than strings.
One caution belongs with money specifically: floats are approximations, and long chains of price arithmetic can accumulate tiny errors that surface as a penny missing. For learning projects floats are fine, but know that Python’s decimal module exists for exact decimal arithmetic when the numbers must be perfect. The path from this article runs naturally in that direction: convert input deliberately, validate it, compute with the right numeric type, and format the result for humans at the end.
Conclusion
input() returns text, and converting that text deliberately is a core Python skill. Use int() for whole numbers, float() for decimals, wrap conversions in a try/except retry loop, and add range checks for values that must be sensible. With a tiny helper function, asking for a number becomes a one-line, crash-proof operation.
Frequently Asked Questions
Why did my addition produce “105” instead of 15?
Because both inputs were strings, and the + operator on strings means join them together. "10" + "5" is "105". Converting each input with int() before adding gives the arithmetic result you expected.
How do I read a number with a decimal comma, like 3,5?
Some locales write decimals with a comma. Replace it before converting: float(text.replace(",", ".")). Apply this only when you know your users use that convention, because in other contexts a comma is a thousands separator and means something different.
What happens if the user just presses Enter?
input() returns an empty string, and both int("") and float("") raise ValueError. The retry-loop pattern handles this naturally: the conversion fails, the message prints, and the question is asked again. No special case is needed.
Can I convert input at the end instead of immediately?
You can, but immediate conversion is clearer and safer. The longer a value travels through your program as text, the more chances for string behaviour — concatenation, alphabetical comparison, repetition — to corrupt your logic. Convert at the door, validate, and work with numbers thereafter.
How do I read a number without showing what the user types?
For ordinary numeric input you do not need secrecy, but the technique exists for values like PIN-style codes: the getpass module in the standard library reads a line without echoing it to the screen. You still receive a string and convert it exactly as this article describes, with the same validation loop. Use it only when privacy genuinely matters, since hidden typing makes correcting mistakes harder for the user.
How do I ask for a yes/no answer as a value?
That is not numeric input, but the same discipline applies: normalise the text with .strip().lower() and compare against accepted forms like "y" and "yes", looping until the answer matches one of them. Predictable normalisation beats hoping users type exactly what you imagined.


Leave a Reply