Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to convert a string to a float?
    text
    copied!<p>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.</p> <p>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). </p> <p>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: </p> <pre><code>ValueError: could not convert string to float: 'stop' </code></pre> <p>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! :)</p> <p>Here is some of my code: </p> <pre><code>count = 0 total = 0 number = float(input("Enter a number (0, or the word 'stop', to stop): ")) while (number != 0): total += number count += 1 print("Your average so far is: " , total / count) number = float(input("Enter a number (0, or the word 'stop', to stop): ")) if (number == 0): if (count == 0): print("") print("Total: 0") print("Count: 0") print("Average: 0") print("") print("Your average is equal to 0. Cool! ") else: print("") print("Total: " , "%.0f" % total) print("Count: " , count) print("Average: " , total / count) </code></pre> <p>Please let me know what I should do. Thanks. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload