cant make this Python code work as intended?
Hi, i am just started learning Python. how can i make it show "done" once at the end? I am just using the basic Python IDE. Thanks
- ?Lv 52 months ago
The print('done') should be after the while do loop and not within it.
- husoskiLv 72 months ago
You can't run whole programs in interactive mode. You can only enter and run single statements.
The statement can be a multi-line compound statement like your while statement above. Other compound statements are if (elif and else are part of the if statement, not separate statements on their own), for, def, etc.
When you do enter a compound statement in interactve mode, you need to add a blank line after the last indented line to let the interpreter know you are done. (This is only needed in interactive mode, not in a stored program or module.)
The final "print('done')" statement is not part of the while statement, so it can't be directly combined with the other statements. (see below for a workaround) To use Idle or command-line interactive mode as intended, enter just the while statement:
>>> while b > 0:
b = b - 1
...and then press Enter a second time after ending that last line to make the while loop run.
If you want to run multiple individual statements as a group, the easiest hack I can think of is to put all of them into a compound if statement:
>>> if True:
b = 5
while b > 0:
b = b - 1
...and press enter to run the if statement. "if True" always runs, just once, so all of the indented lines will run in order after that.
Two final things:
- Don't copy/paste any of that. I had to add extra spaces to make it look like an Idle or Python interactive mode session.
- It's easier to put the statements into a .py source file and run them, either from the command line or directly from an editor window in Idle by just pressing F5 to save and run. Idle is particularly easy to use, and has nice features, like a right-click option after an error to go directly to the source file line that caused it.