Self-Error when entering a string for a question that requires a decimal point

Asked 2 years ago, Updated 2 years ago, 86 views

I make a code to enter the second decimal place

If you enter a string, or if you enter a decimal point incorrectly, Print a print ("Re-enter"). You want to prompt again to enter the second decimal place.

But I can't re-enter the input number.

x= float("Enter a number"."))

while x != float:

    print ("Re-enter")

I'm trying to do it this way, but I can't proceed because there's an error in the while statement. Please lend me your wisdom.

python print while-loop

2022-09-20 17:04

2 Answers

You have to take advantage of the error. You must catch the exception that occurs when you do the following. (In fact, to get complicated, an event where a user tries to enter something other than a number occurs naturally, so it shouldn't be considered an exception.))

x = float('character')

Regarding while control, I will give you only four lines of hints.

x_is_float = False
while x_is_float is False:
    If blah blah blah:
        x_is_float = True


2022-09-20 17:04

It's not an error in the while statement, it's an error in x.

An error would not have occurred when you entered a number.

This is a problem caused by performing the float command, but an error occurs if you float a non-numeric character.

If I were you, I'd take x as follows, and if I succeeded in floating it, I'd end the loop, or I'd get an error, so I'd use exception processing.

while 1:
    x = input ('Please enter a number :')
    try:
        y = float(x)
        break
    except:
        print('Please enter only a number.')


2022-09-20 17:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.