1

I have a code thus far, but I'm trying to prompt the user to enter a number between [0-90], say 20 for example and store it as a float.

The code so far looks like this:

x=input("Choose a number Between [0, 90]")
x=float(20)

The goal is to get them to choose 20; If they choose a different number, it'll quit.

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
Stacey
  • 21
  • 1

2 Answers2

1

Python is a "duck typed" language. Since any variable can be any type, determined at the time of assignment, you need to explicitly check the value input to make sure it's between 0 and 99.

# First Set a standard error message here. 
# Note the use of "{}" which will be filled in using the python method "format" later. 
err = "The value must be a floating point number between 0 and 99. The value '{}' is invalid."

# Then get the value itself.
x=input("Choose a number Between [0, 90]")

# The value "x" will be a string, no matter what is typed. So you must convert it to a float. 
# Because an invalid input (such as "a") will error out, I would use a try/except format. 
try: 
    x=float(x)
except ValueError as e: 
    print(err.format(x))

# Then check the value itself
if ( (x < 0) or (x > 99) ):
    raise ValueError(err.format(x)) 

@עומר דודסון's answer is also correct, in the sense that it will try to convert the input to a float, at the time of input. If an invalid input, such as "a" is entered, it will raise an error...so I would still put it in a try/except...

try: 
    x=float( input("Choose a number Between [0, 90]") )
except ValueError as e: 
    print(err.format(x))

# But you still need to check the value itself
if ( (x < 0) or (x > 99) ):
    raise ValueError(err.format(x)) 
RightmireM
  • 2,381
  • 2
  • 24
  • 42
0

if you want to store the input as a float then use the function "float":

x=float(input("Choose a number Between [0, 90]"))