I have written a code in Python. Now, I want the code to be repeated forever until the receipt of a certain input, using a while loop the condition of which is always true.
The problem is that I receive indentation error. As far as I know, in Python, indentation specifies which part of code is under which. In the situation I described, all of my code should be under this infinite while, but since I am adding the while after writing the code, the indentation is not automatically set. The code is long and I cannot put a tab before every line of my code to take it under the new while. How do I fix this problem?
In C++, I could do this just by adding the while and putting the code in its {}.
Depending on your editor you can indent an entire block of code at once. Pycharm you highlight the code and press tab. On something like VS Code you highlight the block and hold CTRL and press the right square bracket ].
The general pattern I use for "run forever until" is:
keep_running = True
while keep_running:
# code runs forever and returns condition as bool
if condition is True:
keep_running = False # will stop the loop
# or use break
Above is minimal and intended to be easy to grok. There are many ways to go about this type of task, I wanted to present something straight forward. Use of break will also perform in this manner.
As for indentation, mixing tab+space can get weird. Look into flake8 and pylint libraries (there are others) and see what they tell you for code problems.
Edit: Python's indentation can be hard to get used to and setting up your coding environment well is really important. Virtual environments are also VERY IMPORTANT (VENV and PIPENV), do not skip that work if you install any packages. Also important is to learn how to read Python errors (exceptions/tracebacks), they are quite descriptive, but not intuitive at first. If you are coming from C (or PHP, JS, etc) it is important to note that some "slop" you might be used to ignoring will not be tolerated in Python.
Simple:
while True:
print("Hello there")
print("Hello there") is your code running indefinitely.
I see this in programs where people will assign a line/multiple lines of code with "#". I thought this was strictly for commenting. How does this affect an overall program?
For a short answer, it doesn't. The only thing the '#' is used for is making comments inside of your code, nothing more, nothing less.
When you use tkinter, to make some specific shades you will have to put a hex in this '#'
like '#ffffff' or '#00ff00'
This does not affect program, this code with an '#' can be an example of how to use this library or module, but it is being ignored by interpreter, so it does not do anything.
Kinda new to python, coming from a C/C++ development experience. Not to rant, but the indentation and spacing things are kinda becoming the bane of my life. So here is the problem. Take this code snippet, typed sequentially, never erasing or inserting any edit between existing codes.
while condition:
line 1
line 2
line3 #outside the loop
It is working fine. But, suppose, I want to add another instruction inside the loop. (Editing using jupyter notebook and sublime, on Linux) So I add the line as
while condition:
line 1
line 1.5
line 2
line3 #outside the loop
That is when the problem starts. No matter what I try, I can never make it work. It is giving me errors like
line 2
^
IndentationError: unexpected indent
or some variations depending on the circumstances. It seems somehow adding a single line within a large and complicated nested block structure somehow totally messes up the whole thing.
I do not insert the spaces/indents manually, I just let my editor take care of that. When I hit enter, the cursor moves down to the next line, indented at the same level as the previous line (unless the previous line ends with a :, in which case it adds another indentation).
When I need to end a while loop or if block, I just hit the backspace to retract one indentation level. The blocks look perfectly okay by eye inspection, but have no clue how the interpreter sees it.
Any help, on what am I doing wrong, or at least what are the good practices to avoid this problem? Particularly, adding even a single line within an existing nested block seems nigh impossible.
You may mix of using space and tab indentation. You can use either tab or space but not both. However, it's recommend to use space as The PEP8 Python Style Guide
If you are using Visual Studio Code, you can install pylint extension to easily detect such kind of these errors. Something like this:
pylint output
Sublime text editor uses tabs for indentation by default. If you initially used spaces for indentation and edit later, you would have a mix of both spaces and tabs for indentation, which is what is causing the indentation error. This is because Python 3 disallows mixing the use of tabs and spaces for indentation.
The PEP8 Python Style Guide recommends using 4 spaces per indentation level. Go back and replace the tabs with spaces, and the code will work just fine.
(PS: It's easy enough to change the default indentation settings for Sublime)
(Warning: Potential flame-war starter. This is however not my goal, the point here is not to discuss the design choices of Python, but to know how to make the best out of it).
Is there a program, script, method (Unix-based, ideally), to display "virtual" brackets around blocs of code in Python, and to keep them where they are so that the code can still be executed even if indenting is broken ?
I realize that Python only uses indentation to define blocks of code, and that the final program may not contain brackets.
However, I find it very annoying that your program can stop functioning just because of an unfortunate and undetected carriage-return.
So, ideally I would be looking for a plugin in a text editor (kate, gedit...) that would:
Display virtual brackets around blocks of code in my Python program
Keep them in place
Generate dynamically the "correct" Python code with the indentation corresponding to where the brackets belong.
(no flame-war, please !)
I used an editor that does code rollups and understood Python syntax, then I looked for rollups that are in unexpected locations. I don't remember if Kate does that. It's not obvious that there is an issue, but it makes it easier when you are looking for an issue.
I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?
I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting?
The answer is no.
At least, not until something like the following is implemented:
from __future__ import braces
No. Indentation-as-grammar is an integral part of the Python language, for better and worse.
Emacs! Seriously, its use of "tab is a command, not a character", is absolutely perfect for python development.
All of the whitespace issues I had when I was starting Python were the result mixing tabs and spaces. Once I configured everything to just use one or the other, I stopped having problems.
In my case I configured UltraEdit & vim to use spaces in place of tabs.
It's possible to write a pre-processor which takes randomly-indented code with pseudo-python keywords like "endif" and "endwhile" and properly indents things. I had to do this when using python as an "ASP-like" language, because the whole notion of "indentation" gets a bit fuzzy in such an environment.
Of course, even with such a thing you really ought to indent sanely, at which point the conveter becomes superfluous.
I find it hard to understand when people flag this as a problem with Python. I took to it immediately and actually find it's one of my favourite 'features' of the language :)
In other languages I have two jobs:
1. Fix the braces so the computer can parse my code
2. Fix the indentation so I can parse my code.
So in Python I have half as much to worry about ;-)
(nb the only time I ever have problem with indendation is when Python code is in a blog and a forum that messes with the white-space but this is happening less and less as the apps get smarter)
I'm currently using NotePad++. Is
there maybe an IDE that would take
care of the tabs and indenting?
I liked pydev extensions of eclipse for that.
I do not believe so, as Python is a whitespace-delimited language. Perhaps a text editor or IDE with auto-indentation would be of help. What are you currently using?
No, there isn't. Indentation is syntax for Python. You can:
Use tabnanny.py to check your code
Use a syntax-aware editor that highlights such mistakes (vi does that, emacs I bet it does, and then, most IDEs do too)
(far-fetched) write a preprocessor of your own to convert braces (or whatever block delimiters you love) into indentation
You should disable tab characters in your editor when you're working with Python (always, actually, IMHO, but especially when you're working with Python). Look for an option like "Use spaces for tabs": any decent editor should have one.
I agree with justin and others -- pick a good editor and use spaces rather than tabs for indentation and the whitespace thing becomes a non-issue. I only recently started using Python, and while I thought the whitespace issue would be a real annoyance it turns out to not be the case. For the record I'm using emacs though I'm sure there are other editors out there that do an equally fine job.
If you're really dead-set against it, you can always pass your scripts through a pre-processor but that's a bad idea on many levels. If you're going to learn a language, embrace the features of that language rather than try to work around them. Otherwise, what's the point of learning a new language?
Not really. There are a few ways to modify whitespace rules for a given line of code, but you will still need indent levels to determine scope.
You can terminate statements with ; and then begin a new statement on the same line. (Which people often do when golfing.)
If you want to break up a single line into multiple lines you can finish a line with the \ character which means the current line effectively continues from the first non-whitespace character of the next line. This visually appears violate the usual whitespace rules but is legal.
My advice: don't use tabs if you are having tab/space confusion. Use spaces, and choose either 2 or 3 spaces as your indent level.
A good editor will make it so you don't have to worry about this. (python-mode for emacs, for example, you can just use the tab key and it will keep you honest).
Tabs and spaces confusion can be fixed by setting your editor to use spaces instead of tabs.
To make whitespace completely intuitive, you can use a stronger code editor or an IDE (though you don't need a full-blown IDE if all you need is proper automatic code indenting).
A list of editors can be found in the Python wiki, though that one is a bit too exhausting:
- http://wiki.python.org/moin/PythonEditors
There's already a question in here which tries to slim that down a bit:
https://stackoverflow.com/questions/60784/poll-which-python-ideeditor-is-the-best
Maybe you should add a more specific question on that: "Which Python editor or IDE do you prefer on Windows - and why?"
Getting your indentation to work correctly is going to be important in any language you use.
Even though it won't affect the execution of the program in most other languages, incorrect indentation can be very confusing for anyone trying to read your program, so you need to invest the time in figuring out how to configure your editor to align things correctly.
Python is pretty liberal in how it lets you indent. You can pick between tabs and spaces (but you really should use spaces) and can pick how many spaces. The only thing it requires is that you are consistent which ultimately is important no matter what language you use.
I was a bit reluctant to learn Python because of tabbing. However, I almost didn't notice it when I used Vim.
If you don't want to use an IDE/text editor with automatic indenting, you can use the pindent.py script that comes in the Tools\Scripts directory. It's a preprocessor that can convert code like:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
end if
else:
print 'oops!'
end if
end def foobar
into:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar
Which is valid python.
Nope, there's no way around it, and it's by design:
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
Most Python programmers simply don't use tabs, but use spaces to indent instead, that way there's no editor-to-editor inconsistency.
I'm surprised no one has mentioned IDLE as a good default python editor. Nice syntax colors, handles indents, has intellisense, easy to adjust fonts, and it comes with the default download of python. Heck, I write mostly IronPython, but it's so nice & easy to edit in IDLE and run ipy from a command prompt.
Oh, and what is the big deal about whitespace? Most easy to read C or C# is well indented, too, python just enforces a really simple formatting rule.
Many Python IDEs and generally-capable text/source editors can handle the whitespace for you.
However, it is best to just "let go" and enjoy the whitespace rules of Python. With some practice, they won't get into your way at all, and you will find they have many merits, the most important of which are:
Because of the forced whitespace, Python code is simpler to understand. You will find that as you read code written by others, it is easier to grok than code in, say, Perl or PHP.
Whitespace saves you quite a few keystrokes of control characters like { and }, which litter code written in C-like languages. Less {s and }s means, among other things, less RSI and wrist pain. This is not a matter to take lightly.
In Python, indentation is a semantic element as well as providing visual grouping for readability.
Both space and tab can indicate indentation. This is unfortunate, because:
The interpretation(s) of a tab varies
among editors and IDEs and is often
configurable (and often configured).
OTOH, some editors are not
configurable but apply their own
rules for indentation.
Different sequences of
spaces and tabs may be visually
indistinguishable.
Cut and pastes can alter whitespace.
So, unless you know that a given piece of code will only be modified by yourself with a single tool and an unvarying config, you must avoid tabs for indentation (configure your IDE) and make sure that you are warned if they are introduced (search for tabs in leading whitespace).
And you can still expect to be bitten now and then, as long as arbitrary semantics are applied to control characters.
Check the options of your editor or find an editor/IDE that allows you to convert TABs to spaces. I usually set the options of my editor to substitute the TAB character with 4 spaces, and I never run into any problems.
Yes, there is a way. I hate these "no way" answers, there is no way until you discover one.
And in that case, whatever it is worth, there is one.
I read once about a guy who designed a way to code so that a simple script could re-indent the code properly. I didn't managed to find any links today, though, but I swear I read it.
The main tricks are to always use return at the end of a function, always use pass at the end of an if or at the end of a class definition, and always use continue at the end of a while. Of course, any other no-effect instruction would fit the purpose.
Then, a simple awk script can take your code and detect the end of block by reading pass/continue/return instructions, and the start of code with if/def/while/... instructions.
Of course, because you'll develop your indenting script, you'll see that you don't have to use continue after a return inside the if, because the return will trigger the indent-back mechanism. The same applies for other situations. Just get use to it.
If you are diligent, you'll be able to cut/paste and add/remove if and correct the indentations automagically. And incidentally, pasting code from the web will require you to understand a bit of it so that you can adapt it to that "non-classical" setting.