I am just learning python and need to know how to indent a block of code without using the tab button (because, as I have read, tab should not be used).
Example:
in a simple print function
def test(string):
print(string)
print("'" + string + "'")
test('test')
IF now, I want to put the print functions in an if statement
def test(string):
if len(string) > 2:
print(string)
print("'" + string + "'")
test('test')
How can I indent the two print statements without using the 'tab', or having to click on every line and insert 4 spaces? I am very used to selecting all the lines I need to move to the right and pressing tab regardless of program (geany, ipython, notepad++).
I would like to set off following the PEP8 style guide from the introduction into Python.
My concern is not this particular example, but if I have a code block I want to move left or right that is many more lines.
Thanks,
Ivan
It depends on what text editor you're using. I use Notepad++, which is one of the ones you mention, and it has an option to use spaces in place of tabs. So I just enable that for .py files, then I can indent a block by hitting tab exactly as you're used to (and unindent with shift-tab).
Go to settings > preferences > tab settings, select "python" from the list on the right and check the "replace by space" checkbox. Other text editors that offer the same feature will presumably each have their own way of enabling it, and their own way of making it language-specific.
Be aware that pressing tab to change the indentation of a selection is just a UI convention, albeit a common one. It doesn't work for example in Notepad, where hitting tab while text is highlighted behaves the same as typing anything else: replaces the selection with a tab. If you were using Notepad then I'm pretty sure the answer would be "it's not possible". If you use lots of different editors then I think unfortunately you're going to have to investigate each one in turn.
As you have mentioned, PEP8 recommends four spaces for each level of indentation. Many text editors allow you to set tabs to be replaced by a certain number of spaces. So in many cases it is still ok to use tab to program in python, just make sure that it is replaced by four spaces.
I personally use Sublime Text and there seems to be an option to customize Tabs:
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
In the Packages/User/Preferences.sublime-settings. Maybe worth trying that.
Related
def contains_sequence(dna1, dna2):
''' (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
'''
b=False
len2=len(dna2)
i=0
for j in dna1:
temp=dna1[i:i+len2]
if temp == dna2:
b=True
i=i+1
return b
I am new to Python. The program pasted above gives me an error "Inconsistent use of tabs and spaces in indentation" at line "if temp == dna2:" specifically. Can someone please help me out in finding out how the indentation is incorrect?
It means you have mixed up spaces and tabs in the indentation. You have to fix that to be consistent with either tabs or spaces.
If you look carefully at the lines
temp=dna1[i:i+len2]
if temp == dna2:
in your code, you will see that the "space" at the beginning of each line is "constructed" differently. In one case it uses tabs and in the other spaces, or, if both have tabs and spaces then they are used in different combinations.
You can examine this by placing your cursor at the beginning of each line and using the right-arrow key to "walk" your way through the characters. You'll see that the cursor moves differently on each line.
To fix, delete the tabs and spaces at the beginning of each line and re-insert them with the same characters on each line.
To avoid in the future, train yourself to use only the tab key OR the space key to indent, and consider setting your editor to automatically convert tabs to spaces.
Assuming you have a "good" IDE, it's best to set the tab key to make 4 spaces instead of a "tab", that way you have less problems, and it's good practice, for when you will work with other people.
I was almost struct at this problem for quiet some time. I was using CentOS Ec2 and found out that you can:
vim <filename>
Press Escape Key If you're in write/insert mode
:set list
The spaces will be visible as End Of Lines such as $ symbol.
It's helpful.
In my case Visual Studio code ..
Ctrl+Shift+P or View->Command Palette.
Type
Convert Indentation to Spaces
press Enter.
According to the your Doc strings
your code:
b=False
len2=len(dna2)
i=0
for j in dna1:
temp=dna1[i:i+len2]
if temp == dna2:
b=True
i=i+1
return b
This much Big code can be simplified to one line
return dna1.find(dna2)>=0
Also if u are not good with indentations in 'vim' editor its good to practice in IDLE3
If you are copying and pasting code from another source, always copy and paste it on a normal text editor first, then fix the indentation after copying and pasting it in a code editor. This is an easy way to fix this issue.
I saw that there are similar titles to this. But my case seems a little weirder. I somehow used a mixture of PyCharm and Vim (and within Vim I have tabstop=4 and shiftwidth=2), and my Python code seems un-fixabl-y borked, indentation-wise. I first saw that in Vim everything was mis-aligned, so I re-aligned everything; but then when I run it I get an error that there's an unexpected indentation, even though in Vim everything seems perfectly aligned. Here's an example (this is how it looks like in Vim):
for f in files:
for line in f:
items = line.strip().split()
items = items[2:]
items = ' '.join(items).split(', ')
When I run it, I get:
File "getEsSynonymLSAVectors.py", line 136
items = items[2:]
^
IndentationError: unexpected indent
I used PythonTidy, I used reindent, I tried :retab, I tried manual re-aligning - nothing seems to fix this. Any experiences/ advice will be appreciated.
Python treated a tab as 8 spaces by default, if you get indentation borked, you'll generally want to switch the tabs to spaces (or vice versa, but I generally find that spaces are easier to deal with). So make sure to set vim to show tab as 8 spaces wide (:set ts=8), to see what python sees.
To fix tab errors in vim, I usually do the following, first I need to be able to see the tabs, so I enabled highlight search (:set hlsearch) and search for tabs (/\t). Then I eyeball the areas that needs to be retabbed. Next, I try to find the right vim tab width setting for the file (:set ts=n and vary n until everything looks good), enable expand tab (:set et), then run the automatic tab fixing (:retab). When all else fail, retab manually.
If you're using version control, make sure to diff with the files before the changes and manually check that you didn't introduce a bug because of unintentional changes in the indentation level. If you don't use version control, keep a backup and run diff on the files.
Try something like this.
First set appropriate settings.
Always use 4 spaces. So change it to tabs = 4 spaces.
First convert all spaces to tabs.
And then convert all tabs to spaces.
(I use Geany)
It has worked for me before many times.
I am a newbie to python programming. I find that decreasing the indentation of a block of codes in python is quite annoying. For example, given the following code snippet
for i in range(density):
if i < 5:
x, y = rnd(0,shape[1]//2)*2, rnd(0,shape[0]//2)*2
Z[y,x] = 1
....
....
If I comment the if statement, I have to decrease the indentation for lines in the if block one by one, is there a way that I can do this by one key stroke as I increase the indentation of a block of codes by selecting them and press the TAB key? I guess this is environment dependent, so could you please provide solutions to do so in Eclipse+Pydev, VIM, and other common editors?
In vim, you select the block and then press the < key.
In Eclipse you select it and then press SHIFT + TAB.
Every code editor worth its salt has a one-key way to indent and dedent blocks.
You could also replace the if statement with:
if True: # if i < 5:
and leave everything else alone - no indent/dedent to undo later.
Perhaps late for your case, but if useful for others:
SHIFT + TAB will do unindent for the selected text in Eclipse.
Use Preferences-Pydev-Editor settings uncheck change tabs to spaces. It makes detent errors and your problem. And test other options like 4 space tab, 8 space tab and so on.
I can't get the auto-indentations to work properly unless I use the automatic closing of braces, et al (which I don't like), and I see no option allowing one to skip over/out.
Eclipse has a configuration option for this, and Visual Studio doesn't auto-close everything by default, but rather formats the code block after manually entering the closing brace (which I rather prefer).
Surely there's something apart from going all the way over to the "End" key?
Edit / update:
As I consider it bad form to leave a question without a marked answer, would someone with more recent experience with PyCharm (I haven't used it in quite some time) weigh in with a recommendation for the best among the below solutions? Perhaps there's a newer configuration option or simple solution not yet listed?
Press Ctrl-Shift-Enter to close the missing braces on the current line (if any), add the missing colon (if missing) and put the caret into the correctly indented position on the next line.
Shift + Enter will jump past completions and drop you onto the next line.
Ctrl + ] will jump to the end of the current element.
This seems to work in most cases to skip past auto-completions. I find it the most versatile of the options.
Ctrl + [ will jump you to the start of whatever code block you are in.
As previously mentioned Ctrl + Shift + Enter will add any extra auto-completions you might need and drop onto a new line.
A college told me a solution:
First you type this:
def test_foo(
PyCharm inserts self) as soon as you type (
Current state: ^ indicates the cursor position:
def test_foo(self^):
Just type ): and hit ENTER, and you are on the next line.
Since I type with ten fingers Ctrl-Shift-Enter is not a solution for me in such common editing operations.
Why do you dislike the auto-closing brackets? They do not disturb anyone, see:
^ specifies the cursor position
method([a, {b: c^}])
behaves as if no brackets were there if you insert new brackets!
insert a '}':
method([a, {b: c}^])
now insert a ']':
method([a, {b: c}]^)
now insert a ')':
method([a, {b: c}])^
et voila! From a users point of view, if you typed blindly, you can not tell from what you see now if the auto-closing brackets were inserted or not.
Or simply: keep the closing brackets on. IntelliJ did a great work on a lot of small things we want to have intuitively.
This question already has answers here:
Why doesn't Python have multiline comments?
(18 answers)
Closed 9 years ago.
Is there a mechanism to comment out large blocks of Python code?
Right now, the only ways I can see of commenting out code are to either start every line with a #, or to enclose the code in triple quotes: """.
The problem with these is that inserting # before every line is cumbersome and """ makes the string I want to use as a comment show up in generated documentation.
After reading all comments, the answer seems to be "No".
Python does not have such a mechanism. Prepend a # to each line to block comment. For more information see PEP 8. Most Python IDEs support a mechanism to do the block-commenting-with-hash-signs automatically for you. For example, in IDLE on my machine, it's Alt+3 and Alt+4.
Don't use triple-quotes; as you discovered, this is for documentation strings not block comments, although it has a similar effect. If you're just commenting things out temporarily, this is fine as a temporary measure.
Hide the triple quotes in a context that won't be mistaken for a docstring, eg:
'''
...statements...
''' and None
or:
if False: '''
...statements...
'''
The only cure I know for this is a good editor. Sorry.
The only way you can do this without triple quotes is to add an:
if False:
And then indent all your code. Note that the code will still need to have proper syntax.
Many Python IDEs can add # for you on each selected line, and remove them when un-commenting too. Likewise, if you use vi or Emacs you can create a macro to do this for you for a block of code.
In JetBrains PyCharm on Mac use Command + / to comment/uncomment selected block of code. On Windows, use CTRL + /.
M-x comment-region, in Emacs' Python mode.
At least in VIM you can select the first column of text you want to insert using Block Visual mode (CTRL+V in non-windows VIMs) and then prepend a # before each line using this sequence:
I#<esc>
In Block Visual mode I moves to insert mode with the cursor before the block on its first line. The inserted text is copied before each line in the block.
In vi:
Go to top of block and mark it with letter a.
Go to bottom of block and mark it with letter b
Then do
:'a,'b s!^!#!
comm='''
Junk, or working code
that I need to comment.
'''
You can replace comm by a variable of your choice that is perhaps shorter, easy to touch-type, and you know does not (and will not) occur in your programs. Examples: xxx, oo, null, nil.
In Visual Studio using the Python Tools for Visual Studio, blocks can be commented out by Ctrl+K, Ctrl+C and uncommented by Ctrl+K, Ctrl+U.
I use Notepad++ on a Windows machine, select your code, type CTRL-K. To uncomment you select code and press Ctrl + Shift + K.
Incidentally, Notepad++ works nicely as a Python editor. With auto-completion, code folding, syntax highlighting, and much more. And it's free as in speech and as in beer!
In Eclipse + PyDev, Python block commenting is similar to Eclipse Java block commenting; select the lines you want to comment and use Ctrl + / to comment. To uncomment a commented block, do the same thing.
Yes, there is (depending on your editor). In PyDev (and in Aptana Studio with PyDev):
Ctrl + 4 - comment selected block
Ctrl + 5 - uncomment selected block
The only mechanism to comment out Python code (understood as code ignored by the interpreter) is the #.
As you say, you can also use string literals, that are not ignored by the interpreter, but can be completely irrelevant for the program execution.
In Eclipse using PyDev, you can select a code block and press Ctrl + #.
Triple quotes are OK to me.
You can use ''' foo ''' for docstrings and """ bar """ for comments or vice-versa to make the code more readable.
Another editor-based solution: text "rectangles" in Emacs.
Highlight the code you want to comment out, then C-x-r-t #
To un-comment the code: highlight, then C-x-r-k
I use this all-day, every day. (Assigned to hot-keys, of course.)
This and powerful regex search/replace is the reason I tolerate Emacs's other "eccentricities".
On Eric4 there is an easy way: select a block, type Ctrl+M to comment the whole block or Ctrl+alt+M to uncomment.
Use a nice editor like SciTe, select your code, press Ctrl + Q and done.
If you don't have an editor that supports block comments you can use a triple quoted string at the start and the end of your code block to 'effectively' comment it out. It is not the best practice though.