I'm using the below code as a part of something to price an option in Python. It might be the case that this is an inefficient way to get user inputs. I'll take some advice on that. The below code works though.
But my main concerns are as follows:
1) How can I ensure that the user only types "put" or "call" in the first input? I'd like for the loop to restart if anything else is entered
2) How can I go back to just an individual part if they enter something wrong, instead of restarting the whole loop? For example, if they enter everything in the correct format but then mess up on "K" it will restart the entire loop from the beginning. Is there a way to just re-prompt for K and not have to re-enter everything else?
Thanks in advance.
while True:
call_or_put = raw_input("Enter call or put for option type: ")
print "-------------------------"
S = raw_input("Enter a valid price for the underlying asset: ")
try:
S = float(S)
except ValueError:
continue
print "---------------------------"
r = raw_input("Enter the risk-free rate (as a DECIMAL), using 10 year treasury yield: ")
try:
r = float(r)
except ValueError:
continue
print "---------------------------"
t0 = raw_input("Enter a valid number of days (as an integer) until expiration: ")
try:
t0 = int(t0)
except ValueError:
continue
print "---------------------------"
K = raw_input("Enter the strike price: ")
try:
K = float(K)
except ValueError:
continue
if type(S)==float and type(r)==float and type(t0)==int and type(K)==float:
break