PythonIsNewToMe
PythonIsNewToMe

Reputation: 3

Why is float(input() preferrable to just using input()?

I am working my way through projects on rosettacode to learn Python programming. I have tried to research the answer to my question, but I am guessing I don't know enough to Google the answer just right.

The challenge was: In this task, the goal is to input a string and the integer 75000, from the text console.

My code:

Person = input('Enter your name, please:')
print('Hello', Person)
input('Enter 75000: ')
print('Thank you')

The answer in the wiki said in part:

The preferred way of getting numbers from the user is to take the input as a string, and pass it to any one of the numeric types to create an instance of the appropriate number.

number = float(raw_input("Input a number: "))

Python 3.0 equivalent:

number = float(input("Input a number: "))

float may be replaced by any numeric type, such as int, complex, or decimal.Decimal. Each one varies in expected input.

Though my code still worked, I want to understand this way.

Upvotes: 0

Views: 1741

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385980

using float(input("prompt"))1 isn't preferable, it's necessary if you want to actually use the value as a floating point number.

All input coming from the keyboard comes in as a string. If you only use it as a string (such as printing it out, saving to a file, etc), there's no reason to convert it to a floating point number. It's only when you want to use it as an actual number that you need to convert it.


1 You may find your code easier to test, debug, and maintain, if you don't embed functions like this. This is especially true while learning. By splitting it into two statements, you can more easily examine the intermediate values (eg: what input() returns before conversion)

s = input("prompt")
f = float(s)

Upvotes: 0

poke
poke

Reputation: 387707

input() in Python 3 (or raw_input() in Python 2) returns a string. A string is not a float (or an int), so you cannot for example calculate something with it. In order to do that, you have to convert it to a float or an int first. And you do that with float() or int().

So your code “works” in that it takes some input. But the result from that input is a string in both cases, and not an int as originally requested by the task.

Upvotes: 1

Related Questions