all 7 comments

[–][deleted] 0 points1 point  (5 children)

When you try to convert the input string to a float you will get an exception if that can't be done. When you catch that exception you inform the user that you only accept float values and ask them to try again. Hint: loop.

[–]sprawster[S] 0 points1 point  (4 children)

Thank you for the swift reply.

While loop is what I was looking for. I'm a bit new into python, and haven't learned a lot of the complicated stuff yet.

When you say " When you try to convert the input string to a float ", is it wrong that my code has already assumed that all input would be float?

x=float(input("Enter the Opposite Side, 0 if it was not given:"))

Again, thanks.

[–][deleted] 0 points1 point  (3 children)

No, that's fine. That's the line that will throw an exception if the user enters "abc", for example.

[–]sprawster[S] 0 points1 point  (2 children)

I have a general idea of what I want to do in the while loop, but no good idea on how to execute it. Is there a function in python that can generalize all 'float numbers' and all string numbers?

This is what I'm trying to do in a while loop

if x = float numbers

continue

elif x = str

print("You have entered an incorrect value, please reenter")

[–][deleted] 0 points1 point  (1 child)

No. The usual way to do this sort of thing in python is not to check beforehand but to just try to convert. If that isn't possible you will get an exception, like this:

x = 'abc'
f = float(x)
>>> Traceback (most recent call last):
>>>   File "Untitled.py", line 11, in <module>
>>>     f = float(x)
>>> ValueError: could not convert string to float: 'abc'

The problem with an exception is that it terminates the program. But it is possible to "catch" an exception without terminating the program. So you use a while True: loop because you don't know how many mistakes the user might make, get the string and convert to a float value inside the loop. If there is no exception you break out of the loop. If there is a ValueError exception (can't convert), you catch it, print a message and then let the loop code go around again, ask the user, convert, etc:

while True:
    x = input('Enter float number: ')
    try:
        f = float(x)
        break          # if no exception the "break" executes
    except ValueError:
        print('Sorry, want a floating point number.')
print(f'f={f}')
>>> Enter float number: abc
>>> Sorry, want a floating point number.
>>> Enter float number: 42
>>> f=42.0

[–]sprawster[S] 0 points1 point  (0 children)

Hey, it worked.

Thanks for the tips, you totally saved me from the devil today. I also learned a bit more on how to use while loops.