Intercept incorrect entries Python [closed]

So I needed to create a script in Python that allows me to calculate distance from one point to another using coordinates. The first point had fixed coordinates and the coordinates to the second point should be through user input. I managed to create that script. The last thing I have to do is to create a statement that allows me to intercept incorrect entries (e.g., letters instead of numbers, nonsensical Degree inputs) using e.g. try...except. So I'm having a bit trouble here since I'm only getting started with Python. Here's my code:

``````lat1= 47.79
lon1=13.00
name= "Entfernung "
typ= "Km"
userEingabe= input("Geben sie lat2 ein:")
userEingabe2= input("Geben sie lon2 ein:")
lat2 = float(userEingabe)
lon2 = float(userEingabe2)
import math
print(name+str(distanz)+typ)
``````

How can I do this?

If you want to make sure you got a numeric input you can try to use the following `try/except` clause:

``````try:
lat2 = float(userEingabe)
lon2 = float(userEingabe2)
except ValueError:
# alert user, terminate script, etc...
``````

Note that `float()` will raise a `ValueError` if the input is non-numerical.

For nonsensical degree inputs you can check if your values are between a specific range or not:

``````try:
assert -90 <= lat2 <= 90
assert -180 <= lon2 <= 180
except AssertionError:
# alert user, terminate script, etc...
``````

You could modify your code like this so the program keeps asking for lat and lon values if they are not numerical or they don't lie between the defined range

``````import math

lat1 = 47.79
lon1 = 13.00
name = "Entfernung "
typ = "Km"

while True:
userEingabe = input("Geben sie lat2 ein:")
userEingabe2 = input("Geben sie lon2 ein:")
try:
lat2 = float(userEingabe)
lon2 = float(userEingabe2)
except ValueError:
print('Values have to be numeric')
continue
try:
assert -90 <= lat2 <= 90
assert -180 <= lon2 <= 180
except AssertionError:
print('Values have to make sense')
continue
break

# calculate and print distance