#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    5
    Rep Power
    0

    How To Convert String To Float?


    Hi guys,

    I'm currently working on a program in Python and I need to figure out how to convert a string value to a float value.

    The program will ask the user to enter a number, and uses a loop to continue asking for more numbers. The user must enter 0 to stop the loop (at which point, the program will give the user the average of all the numbers they entered).

    What I want to do is allow the user to enter the word 'stop' instead of 0 to stop the loop. I've tried making a variable for stop = 0, but this causes the program to give me the following error message:
    ValueError: could not convert string to float: 'stop'

    So how do I make it so that 'stop' can be something the user can enter to stop the loop? Please let me know what I can do to convert the string to float. Thank you so much for your help!
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    605
    Rep Power
    65
    Function float() will do.
    Like ...
    Code:
    x = float(input("Enter a number: "))
    Last edited by Dietrich; November 17th, 2013 at 06:04 PM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    5
    Rep Power
    0
    Originally Posted by Dietrich
    Function float() will do.
    Can you please elaborate? Where exactly do I put this line of code? What do I do with it? What goes in the parentheses? Please help me! Thanks!
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    Put that line of code into a file.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    5
    Rep Power
    0
    Originally Posted by b49P23TIvg
    Put that line of code into a file.
    No worries, I figured it out. Thanks, though.

IMN logo majestic logo threadwatch logo seochat tools logo