My goal is to create a little program that converts angle from radiant to degree and vice-versa. I need the program to close with no error message from python if the user enters the information to convert in the wrong format.
After assigning the variable ‘angle’ to both values of the input. The angle variable becomes a list type. In norther to exit program with no error message I write this: 'if angle is not list():break'.
The problem is when I do that it exits the program for any type of command entered as an input.
here is my code:
import numpy as np
while 1:
angle=input("Please enter the angle you want to convert,\n\n"\
"If you wish to convert degrees in radiant or vise-versa,\n"\
"follow this format: 'angle/D or R'").split('/')
if angle is not list():break
angle[0]=float(angle[0])
radiant= (angle[0]*(np.pi))/180
degre=((angle[0]*180)/np.pi)
if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D' :
print(radiant,'radiants')
elif angle[1] is 'R':
print(degre,'degrés')
else:break
You can use isinstance(angle, list)
to check if it is a list. But it won't help you achieve what you really want to do.
The following code will help you with that.
question = """Please enter the angle you want to convert.
If you wish to convert degree in radiant or vice-versa.
Follow this format: 'angle/D or R'
"""
while 1:
angle=input(question).split('/')
if not isinstance(angle, list): break # This will never happen
# It will never happen because string.split() always returns a list
# Instead you should use something like this:
if len(angle) != 2 or angle[1] not in ['D', 'R']:
break
try:
angle[0]=float(angle[0])
except ValueError:
break
if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D':
# You could also improve this by taking modulo 360 of the angle.
print((angle[0]*np.pi)/180, 'radiants')
else:
# Just an else is enough because we already checked that angle[1] is either D or R
print((angle[0]*180)/np.pi, 'degrees')