python - How to check if a user input is a float -


I am learning Python hard ways to practice 35. Below is the original code, and we are asked to change it so It can accept numbers in which they do not have just 0 and 1. def gold_room (): Print "This room is full of gold how much do you take?" Next = raw_input ("& gt;") If next to "0" or "1" in the next: Next example: how_much = int (Next) Others: Dead ("Man, learn how to type a number.") If how_much & lt; 50: Print "Well, you're not greedy, you win!"

This is my solution, which runs fine and recognizes the float value:

  def gold_room ( ): Print "This room is full of gold, what percentage do you use?" Next = raw_input ("& gt;") Try: how_much = float (next) except ValueError: print "man, type a number learn how to." Gold_room () if if_much & lt; = 50: Print "Well, you're not greedy, you win!" Looking through similar questions, I got some answers that helped me write another solution, shown in the code below. The problem is that using the isdigit () does not give the user the float value. So if the user said that they want to take 50.5%, then they will tell them how to type a number. It otherwise works for the integer how can I do it?  
 "lang-python prettyprint-override">  def gold_room (): Print "This room is full of gold, what percentage do you take?" Next = raw_input ("& gt;"), while true: if next.isdigit (): how_much = float (next) if how_much < = 50: Print "Well, you are not greedy, you win!" Exit (0) Other: Dead ("You greedy bastard!"): Print "Man, learn how to type numbers." (Next, float, int)    

/ code> move only If the next will already be converted to a string. It is not in this case as you want to convert to use again , if you want to avoid using ... .

I did first instead of < if..else , but to put the code further, as shown below.

  def gold_room (): While correct: Print "This room is full of gold, what percentage do you use?" Try: how_much = float (raw_input ("& gt;")) if if_much & lt; = 50: Print "Well, you're not greedy, you win!" Exit (0) Other: Dead ("You greedy bastard!") Exclude ValueError: Print "Man, learn to type a number."   

This will try to put it in the form of a float and if it fails, then ValueError will be extended which will be caught. To learn more, look at this.

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -