import random
attraktioner =["frittfall","bergodalbana","spökhuset"]classNojesfalt:def __init__(self, attraktion):
self.val = attraktion
self.langd =0
self.alder =0#längdgräns för fritt falldef langdgrans(self):print("")
self.langd = int(input("Hur lång är du i cm? "))if self.langd <140:print("tyvärr, du är för kort, prova något annat")return0elif self.langd >=140:print("håll dig hatten, nu åker vi!")print(" ")return1#åldersgräns för spökhusetdef aldersgrans(self):print("")
self.alder = int(input("Hur gammal är du? "))if self.alder <10:print("tyvärr, du är för ung, prova något annat")return0elif self.alder >=10:print("Gå in om du törs!")print(" ")return1#åker attraktion frittfall lr bergodalbanadef aka(self):print("")print(self.val)
tal = random.randint(0,100)if tal <20:print("åkturen gick åt skogen, bättre lycka nästa gång")elif tal >=20:print("jabbadabbbadoooooooo")return1#går i spökhusetdef aka1(self):print("")print(self.val)
tal = random.randint(0,100)if tal <20:print("du är omringad av spöken och kan inte fortsätta")return0elif tal >=20:print("Buhuuuuuu, buuuhuuuu")return1#programkodprint("Välkommen till nöjesfältet, vad vill du göra?")print(" ")while1:
vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")if vald_attr =="1":
val =Nojesfalt(attraktioner[0])if val.langdgrans()==1:
val.aka()elif vald_attr =="2":
val =Nojesfalt(attraktioner[1])
val.aka()elif vald_attr =="3":
val =Nojesfalt(attraktioner[2])if val.aldersgrans()==1:
val.aka1()elif vald_attr =="4":break
I’m trying to create an application in Python 3.2 and I use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out “inconsistent use of tabs and spaces in indentation” when I try to run the program.
How can I change the spaces into tabs? It’s driving me crazy. (I’m a beginner in programming). I would be glad if I could get some overall tips on my code, if I have done a lot of mistakes I would be happy to hear.
import random
attraktioner = ["frittfall","bergodalbana","spökhuset"]
class Nojesfalt:
def __init__(self, attraktion):
self.val = attraktion
self.langd = 0
self.alder = 0
#längdgräns för fritt fall
def langdgrans(self):
print("")
self.langd = int(input("Hur lång är du i cm? "))
if self.langd < 140:
print("tyvärr, du är för kort, prova något annat")
return 0
elif self.langd >= 140:
print("håll dig hatten, nu åker vi!")
print(" ")
return 1
#åldersgräns för spökhuset
def aldersgrans(self):
print("")
self.alder = int(input("Hur gammal är du? "))
if self.alder < 10:
print("tyvärr, du är för ung, prova något annat")
return 0
elif self.alder >= 10:
print("Gå in om du törs!")
print(" ")
return 1
#åker attraktion frittfall lr bergodalbana
def aka(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("åkturen gick åt skogen, bättre lycka nästa gång")
elif tal >= 20:
print("jabbadabbbadoooooooo")
return 1
#går i spökhuset
def aka1(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("du är omringad av spöken och kan inte fortsätta") return 0
elif tal >= 20:
print("Buhuuuuuu, buuuhuuuu")
return 1
#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")
while 1:
vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
if vald_attr == "1":
val = Nojesfalt(attraktioner[0])
if val.langdgrans() == 1:
val.aka()
elif vald_attr == "2":
val = Nojesfalt(attraktioner[1])
val.aka()
elif vald_attr == "3":
val = Nojesfalt(attraktioner[2])
if val.aldersgrans() == 1:
val.aka1()
elif vald_attr == "4":
break
Make a search and replace to replace all tabs with 4 spaces.
Make sure your editor is set to display tabs as 8 spaces.
Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally – such as when copying and pasting from example code that uses tabs instead of spaces.
If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces → choose Anaconda → click on autoformat. Done. Or press Ctrl + Alt + R.
Generally, people prefer indenting with space. It’s more consistent across editors, resulting in fewer mismatches of this sort. However, you are allowed to indent with tab. It’s your choice; however, you should be aware that the standard of 8 spaces per tab is a bit wide.
Concerning your issue, most probably, your editor messed up. To convert tab to space is really editor-dependent.
On Emacs, for example, you can call the method ‘untabify’.
On command line, you can use a sed line (adapt the number of spaces to whatever pleases you):
sed -e 's;\t; ;' < yourFile.py > yourNedFile.py
回答 5
当使用崇高的文本编辑器时,我能够选择inconsistent use of tabs and spaces in indentation出现错误的代码段,然后选择:
view > indentation > convert indentation to spaces
When using the sublime text editor, I was able to select the segment of my code that was giving me the inconsistent use of tabs and spaces in indentation error and select:
view > indentation > convert indentation to spaces
What I did when the same error popped up: Select everything (Str + A) and press Shift + Tab. So nothing was indented anymore. Now go back to the lines you want to have indented, and put it back how you want it.
In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.
To solve the problem, I just deleted the tab before the line then added four spaces.
If your editor doesn’t recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.
There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:
Then if your code is using spaces, you will see small dots where your code is indented:
And if it is indented using tabs, you will see something like this:
Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,
I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.
Sometimes, tab does mess up while indenting. One way is to obviously use the tab and backspace to correctly indent the code.
Another way is to use space4 times (depending on how much you want to indent).
A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced that line to the previous line and then pressed enter. It automatically indented the line to correct position and I was not getting any error after that.
Hopefully, this should help.
回答 18
我有同样的问题,并使用以下python脚本进行修复。希望对别人有帮助。
这是因为使用制表符和空格来缩进代码。在此脚本中,我将每个选项卡替换为四个空格。
input_file ="source code path here"# e.g. source.py
output_file ="out put file path here"# e.g out.pywith open(input_file,'r')as source:with open(output_file,'a+')as result:for line in source:
line = line.replace('\t',' ')
result.write(line)
I had the same problem and fix it using following python script.
hope it help others.
it is because of using tabs and spaces for indenting code.
in this script I replace each tab with four spaces.
input_file = "source code path here" # e.g. source.py
output_file = "out put file path here" # e.g out.py
with open(input_file, 'r') as source:
with open(output_file, 'a+') as result:
for line in source:
line = line.replace('\t', ' ')
result.write(line)
if you use sublime or any other editor which gives you the tool to replace text you can replace all tabs by four spaces from editor.
Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
[Optional step] Enable search keyword highlighting in Vim (ESC:set hlsearch)
Go to the line where you have this problem (ESC:<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.
I oddly ran into a similar issue with one of my .py files. I simply opened the file in Pycharm and pressed Option+Command+L which correctly formats the file contents in one go.
I suspect I was having trouble because I coded this particular .py file through jupyter labs as opposed to my usual choice of sublime text or Pycharm and therefore ran into some hidden indentation issues many answers here have alluded to
Well I had the same problem and I realised that the problem is that I copied code from another python editor to sublime.
I was working with jupyter notebook and then I copied the code into sublime. Apparently when you make specific modifications (like moving code in functions) then indentation gets messy and this is where the problem comes from.
So just stick to one editor. If you do so, then you will be having no problem.
Try deleting the indents and then systematically either pressing tab or pressing space 4 times. This usually happens to me when I have an indent using the tab key and then use the space key in the next line.