Avoiding indentation in Python else and elif - python

In writing a Python code in Wing or IDLE, inside the if condition, we must have an indentation for each line. But the else and the elif part must be aligned with if. However when I type else: or elif: in a newline, it has an indentation and I must remove it manually. I have seen it in several IDEs like Wing.
Is there any way to avoid indentation for else and elif? Indeed I need this:
if (condition):
do this
else:
do this
But when I type it, it's like:
if (condition)
do this
else:
do this

You seem to believe the editor will somehow know how many lines the indented suites of code should have.
It would be easy to make editors "outdent" if those suites were all one line, but a cursory inspection of any moderately complex Python program will show that is clearly not the case.
Which means it's up to us to indicate the end by outdenting manually, usually with SHIFT-TAB, at the end of the clause.

Related

Begin and End in Python blocks

I am using Python
but the space gap is making my life very hard with it
example
when I use the if statement
if Parm2 == 1:
Ch = "A"
elif Parm2 == 2:
Ch = "B"
elif Parm2 == 3:
Ch = "C"
else:
continue
mdl = CallFunc(Parm2)
print("XX Always Print XX")
now the "XX Always Print XX" should be printed regardless
but due to my mistake it is inside the if statement which cause me long time to find
the actual if statement is nested and longer
I wonder if there is a method I can use begin/end or {} in such statements in Python
something like
UPDATE
for the people who focus on the IF statement
if Parm2 == 1:
{
Ch = "A"
}
elif Parm2 == 2:
{
Ch = "B"
}
elif Parm2 == 3:
{
Ch = "C"
}
else:
{
mdl = CallFunc(Parm2)
}
print("XX Always Print XX")
Happy now??
ok now how to get the brackets work in Python?
Python is indentation based. Yeah, its harder to read and easier to make mistakes like you indicated, but that's what it is.
Think about downloading an IDE for python, like Pycharm, they are helpful for identifying errors like this one, they also have an "auto-indent" feature. But no, Python is indentation based.
What the Python designers realized is that braces or begin/end keywords are mostly noise to human programmers. They generally recognize the structure of code by its layout. For instance, if you were to write the C code:
if (condition)
x = y;
w = z;
a human would often not notice that the braces are missing, and assume that both assignments are controlled by the condition. Writing code like this is a common error, especially when you start with a block that has just one statement (so the braces are optional and were omitted), and forget to add braces when a second statement is added. (See Why is it considered a bad practice to omit curly braces?).
Conversely, if you write
if (condition) {
x = y;
w = z;
}
it looks like w = z; is not part of the conditional.
Braces mainly exist for the benefit of software that processes code (compilers, editors, IDEs), they make it easier for them to detect groups of code. The Python designers decided to mirror the way humans read code in their parser, rather than forcing humans to adapt to the computer's needs.
Braces allow for more flexible code layout, but in practice it's usually condiered wrong to take advantage of this. Writing code like
while (something) { statement1; statement2;
statement3; }
is less readable than
while something:
statement1
statement2
statement3
Python does allow some flexibility: You can separate statements on the same line with ;, and put the contents of a conditional on the same line after the :. But writing like this is not considered Pythonic, and should be used only in very special circumstances (this blog post describes those cases).
There's always some adjustment necessary when you're learning a new programming language and you're accustomed to the patterns of the languages you previously used (many programmers have refused to learn Lisp, because of its Lots of Irritating, Stupid Parentheses). But give it a little time and you'll get used to it.
This shows how you can hack it:
if True: {
print("hello")
}
If you do a google search for "python what if you don't want to use indentation for blocks" you might get:
peach pit python indentation
Programmers familiar with other languages often bristle at the thought that indentation matters: Many programmers like the freedom to format their code how they please. However, Python indentation rules are quite simple, and most programmers already use indentation to make their code readable. Python simply takes this idea one step further and gives meaning to the indentation.
i.e. they force you not to use indentation.
My problem with this is that I love to use emacs auto-indentation to reindent the whole code file but this totally screws up the indentation in python; in C or C++ this finds the indentation problems and makes them evident; in python it loses all your information and changes the meaning of the program;
Don't get me wrong I want to use BOTH rigorous indentation AND curly braces;
You can use the hack above to "circumvent" python indentation but when writing code for anyone other than yourself it won't be popular.

"Expected an indented block" What to do?

I'm new to programming and don't know what this means. Please tell me what to do to my code for my assessment. It doesn't highlight the problem when I run it and I don't know what to do. Please help me.
To be honest, reading a Python tutorial would probably do you better. In any case, however...
Python is an indentation-based language. This means anytime you enter a new "block" (code that belongs to a statement), you need to indent your code by one level. Here are two examples, one incorrect and one correct:
if 5 < 10:
print "5 is less than 10! Wow! Thanks, math!"
print "I'm so glad Python told me."
This is a syntax error, since the print statement belongs to the if statement, and is therefore a new block. It should be indented, but in this case it wasn't, so it's an error.
if 5 < 10:
print "5 is less than 10! Wow! Thanks, math!"
print "I'm so glad Python told me."
print "This is printed in any case, since it doesn't belong to the above block."
Here is the fixed verion. Notice the four spaces in the beginning of the second line? That's called "indentation". Any subsequent lines indented to the same level will be part of the block. Generally, you press TAB to indent in your text editor. The last line, however, is not indented and will therefore run regardless of whether the if statement evaluates to True or not.

for loop code block

I was reading the tutorial about python here and was wondering that if the for loop does not have a block like this {}, how would we know which block of code is in the for loop. Are we going to have to read it base on the indentation of the code? Or did I miss something fundamental about python? And while I was trying out some python code in notepad++ when I was in the for loop and create a new line in the middle of my code it for some reason made the line of code and everything above it a block of code while everything else below something different. Again am I missing something? I hope it's not bad programming practice.
Python runs everything on indentation. The indentation level is how it knows what goes with what.
For example, this works:
for i in range(10):
print i
But this blows up with an IndentationError:
for i in range(10):
print i
From docs:
Leading whitespace (spaces and tabs) at the beginning of a logical
line is used to compute the indentation level of the line, which in
turn is used to determine the grouping of statements.

Python indentation in "empty lines"

Which is preferred ("." indicating whitespace)?
A)
def foo():
x = 1
y = 2
....
if True:
bar()
B)
def foo():
x = 1
y = 2
if True:
bar()
My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most of the editors out there are broken?
If you use A, you could copy paste your block in python shell, B will get unexpected indentation error.
The PEP 8 does not seem to be clear on this issue, although the statements about "blank lines" could be interpreted in favor of B. The PEP 8 style-checker (pep8.py) prefers B and warns if you use A; however, both variations are legal. My own view is that since Python will successfully interpret the code in either case that this doesn't really matter, and trying to enforce it would be a lot of work for very little gain. I suppose if you are very adamantly in favor of one or the other you could automatically convert the one to the other. Trying to fix all such lines manually, though, would be a huge undertaking and really not worth the effort, IMHO.
Adding proper indentation to blank lines (style A in the question) vastly improves code readability with display whitespace enabled because it makes it easier to see whether code after a blank line is part of the same indentation block or not.
For a language like Python, where there is no end statement or close bracket, I'm surprised this is not part of PEP. Editing Python with display whitespace on is strongly recommended, to avoid both trailing whitespace and mixed indentation.
Compare reading the following:
A)
def foo():
....x = 1
....y = 2
....
....if True:
........bar()
B)
def foo():
....x = 1
....y = 2
....if True:
........bar()
In A, it is far clearer that the last two lines are part of foo. This is even more useful at higher indentation levels.
That empty line belongs to foo(), so I would consider A to be the most natural. But I guess it's just a matter of opinion.
TextMate breaks block collapsing if you use B, and I prefer A anyway since it's more "logical".
My experience in open-source development is that one should never leave whitespace inside blank lines. Also one should never leave trailing white-space.
It's a matter of coding etiquette.
I wouldn't necessarily call the first example "broken", because I know some people hate it when the cursor "jumps back" when moving the cursor up or down in code. E.g. Visual Studio (at least 2008) automatically prevents this from happening without using any whitespace characters on those lines.
B is preferred - i.e. no indentation. PEP 8 says:
Avoid trailing whitespace anywhere. Because it's usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don't preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.
Emacs does B) for me, but I really don't think it matters. A) means that you can add in a line at the correct indentation without any tabbing.
vi implicitly discourages the behaviour in A because the {/} navigations no longer work as expected. git explicitly discourages it by highlighting it in red when you run git diff. I would also argue that if a line contains spaces it is not a blank line.
For that reason I strongly prefer B. There is nothing worse than expecting to skip six or so lines up with the { motion and ending up at the top of a class def.

Is there a way to convert indentation in Python code to braces?

I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
There's a solution to your problem that is distributed with python itself. pindent.py, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have to grab it from svn.python.org if you are running on Linux or OSX.
It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command:
pindent.py -c myfile.py
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
Where the original myfile.py was:
def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
else:
print 'oops!'
You can also use pindent.py -r to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation.
For example, running pindent.py -r myfile.py will convert the following code in myfile.py into the same properly indented (and also commented) code as produced by the pindent.py -c example above:
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
I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help.
I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited.
I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python?
I'd assume that you use a screen reader here however for the output? So the tabs would seem "invisible" to you? With a Braille output, it might be easier to read, but I can understand exactly how confusing this could be.
In fact, this is very interesting to me. I wish that I knew enough to be able to write an app that will do this for you.
I think it's definately something that I'll put in a bug report for, unless you've already done so yourself, or want to.
Edit: Also, as noted by John Millikin There is also PyBraces Which might be a viable solution to you, and may be possible to be hacked together dependant on your coding skills to be exactly what you need (and I hope that if that's the case, you release it out for others like yourself to use)
Edit 2: I've just reported this to the python bug tracker
Although I am not blind, I have heard good things about Emacspeak. They've had a Python mode since their 8.0 release in 1998 (they seem to be up to release 28.0!). Definitely worth checking out.
You should be able to configure your editor to speak the tabs and spaces -- I know it's possible to display whitespace in most editors, so there must be an accessibility option somewhere to speak them.
Failing that, there is pybraces, which was written as a practical joke but might actually be useful to you with a bit of work.
If you're on Windows, I strongly recommend you take a look at EdSharp from:
http://empowermentzone.com/EdSharp.htm
It supports all of the leading Windows screenreaders, it can be configured to speak the indentation levels of code, or it has a built in utility called PyBrace that can convert to and from braces syntax if you want to do that instead, and it supports all kinds of other features programmers have come to expect in our text editors. I've been using it for years, for everything from PHP to JavaScript to HTML to Python, and I love it.
All of these "no you can't" types of answers are really annoying. Of course you can.
It's a hack, but you can do it.
http://timhatch.com/projects/pybraces/
uses a custom encoding to convert braces to indented blocks before handing it off to the interpreter.
As an aside, and as someone new to python - I don't accept the reasoning behind not even allowing braces/generic block delimiters ... apart from that being the preference of the python devs. Braces at least won't get eaten accidentally if you're doing some automatic processing of your code or working in an editor that doesn't understand that white space is important. If you're generating code automatically, it's handy to not have to keep track of indent levels. If you want to use python to do a perl-esque one-liner, you're automatically crippled. If nothing else, just as a safeguard. What if your 1000 line python program gets all of its tabs eaten? You're going to go line-by-line and figure out where the indenting should be?
Asking about it will invariably get a tongue-in-cheek response like "just do 'from __ future __ import braces'", "configure your IDE correctly", "it's better anyway so get used to it" ...
I see their point, but hey, if i wanted to, i could put a semicolon after every single line. So I don't understand why everyone is so adamant about the braces thing. If you need your language to force you to indent properly, you're not doing it right in the first place.
Just my 2c - I'm going to use braces anyway.
I appreciate your problem, but think you are specifying the implementation instead of the problem you need solved. Instead of converting to braces, how about working on a way for your screen reader to tell you the indentation level?
For example, some people have worked on vim syntax coloring to represent python indentation levels. Perhaps a modified syntax coloring could produce something your screen reader would read?
Searching an accessible Python IDE, found this and decided to answer.
Under Windows with JAWS:
Go to Settings Center by pressing JawsKey+6 (on the number row above the letters) in your favorite text editor. If JAWS prompts to create a new configuration file, agree.
In the search field, type "indent"
There will be only one result: "Say indent characters". Turn this on.
Enjoy!
The only thing that is frustrating for us is that we can't enjoy code examples on websites (since indent speaking in browsers is not too comfortable — it generates superfluous speech).
Happy coding from another Python beginner).
I use eclipse with the pydev extensions since it's an IDE I have a lot of experience with. I also appreciate the smart indentation it offers for coding if statements, loops, etc. I have configured the pindent.py script as an external tool that I can run on the currently focused python module which makes my life easier so I can see what is closed where with out having to constantly check indentation.
There are various answers explaining how to do this. But I would recommend not taking this route. While you could use a script to do the conversion, it would make it hard to work on a team project.
My recommendation would be to configure your screen reader to announce the tabs. This isn't as annoying as it sounds, since it would only say "indent 5" rather than "tab tab tab tab tab". Furthermore, the indentation would only be read whenever it changed, so you could go through an entire block of code without hearing the indentation level. In this way hearing the indentation is no more verbose than hearing the braces.
As I don't know which operating system or screen reader you use I unfortunately can't give the exact steps for achieving this.
Edsger Dijkstra used if ~ fi and do ~ od in his "Guarded Command Language", these appear to originate from the Algol68. There were also some example python guarded blocks used in RosettaCode.org.
fi = od = yrt = end = lambda object: None;
class MyClass(object):
def myfunction(self, arg1, arg2):
for i in range(arg1) :# do
if i > 5 :# then
print i
fi
od # or end(i) #
end(myfunction)
end(MyClass)
Whitespace mangled python code can be unambiguously unmangled and reindented if one uses
guarded blocks if/fi, do/od & try/yrt together with semicolons ";" to separate statements. Excellent for unambiguous magazine listings or cut/pasting from web pages.
It should be easy enough to write a short python program to insert/remove the guard blocks and semicolons.

Categories