0

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.

Kai
  • 3
  • 3
  • 6
    Why does that need to be expressed as `try..except` blocks? It seems fine as it is. – TigerhawkT3 Nov 29 '15 at 12:39
  • I just though it would be neater, also I'm still trying to learn and part of that process is trying to find alternate ways of doing things. – Kai Nov 29 '15 at 12:50
  • In general your exceptions should be **exceptional**. There is some overhead to them, so for normal code flow prefer logic statements. – Tomasz Kaminski Nov 29 '15 at 13:01
  • Ok so as a general case I will try to avoid try...except blocks and focus on logic statements. =) – Kai Nov 29 '15 at 13:04
  • Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – GingerPlusPlus Nov 29 '15 at 14:03

2 Answers2

1

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.

jimkokko5
  • 78
  • 1
  • 11
0

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 raises 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.')
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
  • The problem I have is distinguishing between which while statement to break, for example if choice = y then I want to break only the nested one, if choice = n then I want to break both and else I would like to break none. – Kai Nov 29 '15 at 14:32