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. This is my solution, which runs fine and recognizes the float value: I did first instead of < This will try to put it in the form of a float and if it fails, then 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!"
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
... .
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."
ValueError will be extended which will be caught. To learn more, look at this.
Comments
Post a Comment