I’m attempting to learn Python, but I’m having some issues with it so far. For example, I’m having trouble getting this loop to break, even after looking to Stack Overflow for a solution:
choice = -1 while choice != 0: # Code that asks what the user wants to do, etc. When 0 is chosen, the loop doesn't break. choice = raw_input() # Exit the loop. if choice == 0: break
I read that the while part is ignored after it’s run, which seems strange to me, since every other language I have used checks that line every time. That’s why the line that reads
if choice == 0: break is necessary.
If I ever figure it out, I’ll update this post. Conversely, if anyone can push me in the right direction, the comments on this post are open.
UPDATE: I was checking the
choice variable incorrectly. The raw_input is actually coming in as a string, which would be checked like this:
if choice == '0': break
Or, you can force it as an int, like so…:
choice = int(raw_input())
…and use the original integer check, which might be safer. You can also use
float() in order to force input to be converted into a floating point number.
In my defense, I haven’t worked with a strictly-typed language in years, so this is a nice refresher. I’m posting this because I’m told that Python is a good programming language for novices and I know that when I was fairly novice, I needed help understanding typing. More on this later, I suppose.