Reputation: 3
I have been trying to convert some code into a try statement but I can't seem to get anything working.
Here is my code in pseudo code:
start
run function
check for user input ('Would you like to test another variable? (y/n) ')
if: yes ('y') restart from top
elif: no ('n') exit program (loop is at end of program)
else: return an error saying that the input is invalid.
And here is my code (which works) in python 3.4
run = True
while run == True:
spuriousCorrelate(directory)
cont = True
while cont == True:
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
cont = False
elif choice == 'n':
run = False
cont = False
else:
print('This is not a valid answer please try again.')
run = True
cont = True
Now what is the proper way for me to convert this into a try statement or to neaten my code somewhat?
This isn't a copy of the mentioned referenced post as I am trying to manage two nested statements rather than only get the correct answer.
Upvotes: 0
Views: 61
Reputation: 5606
Ok so as a general case I will try to avoid try...except blocks
Don't do this. Use the right tool for the job.
Use raise
to signal that your code can't (or shouldn't) deal with the scenario.
Use try-except
to process that signal.
Now what is the proper way for me to convert this into a try statement?
Don't convert.
You don't have anything that raise
s in your code, so there is no point of try-except
.
What is the proper way to neaten my code somewhat?
Get rid of your flag variables (run
, cont
). You have break
, use it!
This is prefered way of imlementing do-while
, as Python docs says; unfortunately, I cannot find it to link it right now.
If someone finds it, feel free to edit my answer to include it.
def main()
while True: # while user wants to test variables
spuriousCorrelate(directory) # or whatever your program is doing
while True: # while not received valid answer
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
break # let's test next variable
elif choice == 'n':
return # no more testing, exit whole program
else:
print('This is not a valid answer please try again.')
Upvotes: 0
Reputation: 88
If you want to make your code neater, you should consider having
while run:
instead of
while run == True:
and also remove the last two lines, because setting run
and cont
to True
again isn't necessary (their value didn't change).
Furthermore, I think that a try - except
block would be useful in the case of an integer input, for example:
num = input("Please enter an integer: ")
try:
num = int(num)
except ValueError:
print("Error,", num, "is not a number.")
In your case though I think it's better to stick with if - elif - else
blocks.
Upvotes: 1