0

I'm trying to make a very basic calculator to familiarize myself with the basics of python. Part of the code involves asking for inputs and setting those as different variables, but the variables put in as inputs are stored as strings, even though they're entered as numbers:

def change_x_a():
    velocity_i = input("Initial Velocity?")
    velocity_f = input("Final Velocity?")
    time = input("Time?")
    float(velocity_i)
    float(velocity_f)
    float(time)
    answer = (0.5*(velocity_i+velocity_f)*time)
    print(answer)

Is there a fix for this?

1
  • Please fix your indentation. Commented Nov 24, 2013 at 20:09

3 Answers 3

6

float() doesn't modify the variable you pass it. Instead, it converts the value you give it and returns a float.

So

float(velocity_i)

by itself does nothing, where

velocity_i = float(velocity_i)

will give the behavior you're looking for.


Keep in mind that float() (and the other type-conversion functions) will throw an exception if you pass them something they're not expecting. For a better user experience, you should handle these exceptions1. Typically, one does this in a loop:

while True:
    try:
        velocity_i = float(input("Initial Velocity?"))
        break               # Valid input - stop asking
    except ValueError:
        pass                # Ignore the exception, and ask again

We can wrap this behavior up into a nice little function to make it more re-usable:

def get_input(prompt, exptype):
    while True:
        try:
            return exptype( input(prompt) )
        except ValueError:
            pass                # Ignore the exception, and ask again

and call it like this:

val_f = get_input('Give me a floating-point value:', float)
val_i = get_input('Give me an integer value:', int)

1 - Wow, I just realized that I independently wrote almost the exact same code as the Python tutorial, which I linked to, after the fact.

Sign up to request clarification or add additional context in comments.

Comments

1

You can convert the inputs to float when you take them from the user.

Try

velocity_i = float(input("Initial Velocity?")

And so on.

Comments

1

Yes. Simply convert it to a float:

velocity_i = float(input("Initial Velocity?"))

or an integer:

velocity_f = int(input("Final velocity?"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.