Ошибка unexpected unindent

Я пытался создать телеграмм-бота
вот код

import telebot;
bot = telebot.TeleBot('####');
message_handler(content_types=['text'])
def get_text_messages(message):
    @bot.message_handler(content_types=['text', 'document', 'audio'])
if message.text == "Привет":
    bot.send_message(message.from_user.id, "Привет, чем я могу тебе помочь?")
elif message.text == "/help":
    bot.send_message(message.from_user.id, "Напиши привет")
else:
    bot.send_message(message.from_user.id, "Я тебя не понимаю. Напиши /help.")
bot.polling(none_stop=True, interval=0)

Сразу говорю, я знаю питон плохо.
когда в консоли запускаю, выдает ошибку:
File «C:UsersmaksbDesktopBotbot.py», line 6
if message.text == «Привет»:
IndentationError: unexpected unindent
Помогите пожалуйста :(


  • Вопрос задан

    более года назад

  • 2212 просмотров

Пригласить эксперта

Что-то вы намудрили с расположением декораторов. Поучите сначала основы языка.

import telebot
bot = telebot.TeleBot('####')

@bot.message_handler(content_types=['text'])
def get_text_messages(message): 
    if message.text == "Привет":
        bot.send_message(message.from_user.id, "Привет, чем я могу тебе помочь?")
    elif message.text == "/help":
        bot.send_message(message.from_user.id, "Напиши привет")
    else:
        bot.send_message(message.from_user.id, "Я тебя не понимаю. Напиши /help.")

bot.polling(none_stop=True, interval=0)

def get_text_messages(message):
    @bot.message_handler(content_types=['text', 'document', 'audio'])
    if message.text == "Привет":
        bot.send_message(message.from_user.id, "Привет, чем я могу тебе помочь?")
    elif message.text == "/help":
        bot.send_message(message.from_user.id, "Напиши привет")
    else:
        bot.send_message(message.from_user.id, "Я тебя не понимаю. Напиши /help.")
    bot.polling(none_stop=True, interval=0)


  • Показать ещё
    Загружается…

05 июн. 2023, в 23:42

300 руб./за проект

05 июн. 2023, в 23:25

25000 руб./за проект

05 июн. 2023, в 22:21

1500 руб./за проект

Минуточку внимания

IndentationError: unexpected unindent WHY???

#!/usr/bin/python
import sys
class Seq:
    def __init__(self, id, adnseq, colen):
        self.id     = id
        self.dna    = adnseq
        self.cdnlen = colen
        self.prot   = ""
    def __str__(self):
        return ">%sn%sn" % (self.id, self.prot)
    def translate(self, transtable):
        self.prot = ""
        for i in range(0,len(self.dna),self.cdnlen):
            codon = self.dna[i:i+self.cdnlen]
            aa    = transtable[codon]
            self.prot += aa
    def parseCommandOptions(cmdargs):
        tfname = cmdargs[1]
        sfname = cmdargs[2]
        return (tfname, sfname)
    def readTTable(fname):
        try:
            ttable = {}
            cdnlen = -1
            tfile = open(fname, "r")
            for line in tfile:
                linearr = line.split()
                codon   = linearr[0]
                cdnlen  = len(codon)
                aa      = linearr[1]
                ttable[codon] = aa
            tfile.close()
            return (ttable, cdnlen)
    def translateSData(sfname, cdnlen, ttable):
        try: 
            sequences = []
            seqf = open(seq_fname, "r")
            line = seqf.readline()
            while line:
                if line[0] == ">":
                    id = line[1:len(line)].strip()
                    seq = ""
                    line = seqf.readline()
                    while line and line[0] != '>':
                        seq += line.strip()
                        line = seqf.readline()  
                    sequence = Seq(id, seq, cdnlen)
                    sequence.translate(ttable)
                    sequences.append(sequence)
            seqf.close()
            return sequences    
    if __name__ == "__main__":
        (trans_table_fname, seq_fname) = parseCommandOptions(sys.argv)
        (transtable, colen) = readTTable(trans_table_fname)
        seqs = translateSData(seq_fname, colen, transtable)
        for s in seqs:
            print s

It says:

 def translateSeqData(sfname, cdnlen, ttable):
   ^
IndentationError: unexpected unindent

WHY? I have checked a thousands times and I can’t find the problem. I have only used Tabs and no spaces. Plus, sometimes it asks to define the class. Is that Ok?

Python indentation is a part of the syntax. It’s not just for decoration.

You’ll learn what these errors mean and how to solve them:

  • IndentationError: unexpected indent
  • IndentationError: expected an indented block
  • IndentationError: unindent does not match any outer indentation level
  • IndentationError: unexpected unindent

So if you want to learn how to solve those errors, then you’re in the right place.

Let’s kick things off with error #1!

Polygon art logo of the programming language Python.

How to Solve IndentationError: unexpected indent in Python

Python is a beautiful language. One of the key features of this beauty is the lack of curly braces and other symbols that mark the beginning and end of each block. 

Even in C it is considered a good practice to indent, denoting different levels in the code. Compare the same C ++ code with and without indentation. First with the indentation:

#include <iostream>
#include <windows.h>
#include<time.h>
using namespace std;
void main()
{
    srand (unsigned (time(NULL)));
    int a,b,i;
    cout<<"Guess number game".nn";
    a=rand()%10+1;
    cout<<"AI conceived a number from 1 to 10.n";
    cout<<"Enter your guess and press <Enter>nn";
    for(i=1;i<3;i++)
    {
        cout<<"--->";
        cin>>b;
        if(b==a)
        {
            cout<<"You won! Congrats!n";
            cout<<"You guessed with "<<i<<" try!n";
            break;
        }
        if(b!=a)
        {
            cout<<"No, that's the other number. Try again!n";
        }
    }
    if(b!=a&&i==3)
    {
        cout<<"You lose!n";
    }
}

And the same code without indentation:

#include <iostream>
#include <windows.h>
#include<time.h>
using namespace std;
void main()
{
srand (unsigned (time(NULL)));
int a,b,i;
cout<<"Guess number gamen";
a=rand()%10+1;
cout<<"AI conceived a number from 1 to 10n";
cout<<"Enter your guess and press <Enter>n";
for(i=1;i<3;i++)
{
cout<<"--->";
cin>>b;
if(b==a)
{
cout<<"You won! Congrats!n";
cout<<"You guessed with "<<i<<" try!n";
break;
}
if(b!=a)
{
cout<<"No, that's the other number. Try again!n";
}
}
if(b!=a&&i==3)
{
cout<<"You lose!n";
}
}

Both codes will compile and run, but the indented code is a lot easier to read. In the second case, it isn’t clear which parenthesis goes with which. 

In Python, parentheses aren’t needed, but indentation is. This is what the C++ program would look like in Python:

from random import randint
print("Guess a number game!")
a = randint(1, 11)
print("AI conceived a number from 1 to 10")
print("Enter your guess and press <Enter>")
for i in range(3):
    b = int(input("-->"))
    if a == b:
        print("You won! Congrats!")
        print(f"You guessed with {i+1} try!")
        break
    else:
        print("No, that's the other number. Try again!")
else:
    print("You lose!")
Guess a number game!
AI conceived a number from 1 to 10
Enter your guess and press <Enter>
-->4
You won! Congrats!
You guessed with 1 try!

However, there is a downside to this beauty. If you make a mistake in the indentation, the program will be inconsistent, which will lead to errors when it’s running. 

Perhaps, this is a better option than changing the indentation and not getting the error, but changing the meaning of the program. 

The error IndentationError: unexpected indent is one that results from wrong indentation. It happens when there are no keywords in front of the indentation. Here’s an example:

name = "John Smith"
  print("Hi, ", name)
File "<ipython-input-2-0ae5732b16d5>", line 2
    print("Hi, ", name)
    ^
IndentationError: unexpected indent

Python expects a keyword line to come before an indented line. List of keywords followed by an indented line:

  • class: class definition
  • def: function definition
  • for: a loop with a parameter
  • while: a loop with a condition
  • if, elif, else: conditional operator
  • try, except, finally: exception handling
  • with: a context operator

Python warns you if it finds a line that’s indented, but the previous line doesn’t have these keywords.

How to Solve IndentationError: unexpected indent error in Python

You’ll get a similar error if you don’t indent after a keyword, here’s an example:

for _ in range(10):
print("Hello!")
File "<ipython-input-33-2c027d903716>", line 2
    print("Hello!")
        ^
IndentationError: expected an indented block

IndentationError: expected an indented block happens when you start a construct that assumes you have at least one indented block, but you didn’t indent this.

Tense and serious programmer looking at data on the computer.

This is an easy fix. Just indent a block that’s inside a loop or other appropriate construction.

Python uses spaces for indentation, and tabs are automatically converted to four spaces in Python 3 editors. 

Another feature is that the number of indent spaces can be any, but inside the block they’re the same. 

Since using different numbers of indentations can be confusing, PEP8 recommends exactly four spaces per level of indentation:

a = -1
if a > 0:
   print("Positive")
elif a < 0:
  print("Negative")
else:
 print("Zero")
Negative

This code is possible, it won’t cause an error, but it’ll make your code look terrible to people who’ll read it later.

Often, the IndentationError: unexpected indent error shows up when copying code from any source. 

This is a reason why you shouldn’t mindlessly copy-paste code from somewhere.When you borrow code, it’s always best to retype it.

So there won’t be as many errors when you run this code later. And you better understand what you copied. 

Even in your very first program, you can get this error if you copy the code along with the layout characters:


  print("Hello")
File "<ipython-input-16-c3b57afc4f5f>", line 2
    print("Hello")
    ^
IndentationError: unexpected indent

Another copying error can happen when you edit your code in a text editor without the ability to replace tabs with 4 spaces, such as Notepad++, and use both tabs and spaces for indentation. 

This error is the hardest to figure out because it looks like the code’s on the same line.

The first line has a tab and the second has 4 spaces, which is an entirely different level of indentation for a Python interpreter:

    print("Hello")
    print("World!")

For this error, you can either remove or replace all of the indents, or enable service characters, in Notepad++ this looks like this:

Screenshot Notepad++ Intend

Now you can just replace the tabs with spaces.

How to Solve IndentationError: unindent does not match any outer indentation level in Python

Another error that happens when copying code or when your attention wanders is IndentationError: unindent does not match any outer indentation level. Let’s look at some code that causes such an error:

a = 2
b = 3
for i in range(b):
    if a < i:
        print("Less")
    else:
        print("More")
   print("Round ", i, " finished!")

Draw vertical lines along the indentation levels. We have three indentation levels here: –

  • Original (no indentation)
  • First level is the block inside the loop
  • Second level is the block inside the conditional statement
screenshot_vertical_lines_python

When the lines are drawn, it becomes obvious that the indentation is not in line with the print statement. This line doesn’t belong to any of the existing indentation levels.

You need one more space, then the code will run:

a = 1
b = 3
for i in range(b):
    if a < i:
        print("Less")
    else:
        print("More")
    print("Round ", i, " finished!")
More
Round  0  finished!
More
Round  1  finished!
Less
Round  2  finished!

One way to get around this kind of error is to use automatic code formatters based on PEP8 standards, like autopep8 or Black.

These projects are not primarily intended to fix bugs, but to bring the code up to PEP8 standard, and to maintain code consistency in the project. 

Serious programmer creating a computer software.

When you start out with Python, it is helpful to use these utilities to make beautiful code. But you shouldn’t just do this carelessly. Pay attention to the inaccuracies that such utilities fix.

A much rarer error is IndentationError: unexpected unindent. Using the try-except operator causes it only under certain conditions. 

If you write try, you have to include the except keyword. But if you have just a try without an except, you get SyntaxError: invalid syntax:

try:
    print(0)
print(1)

But you’ll get an IndentationError: unexpected unindent if you try to use try-except inside a function, loop, condition, or context. 

The Python interpreter walks through the code and finds the try keyword, and searches down the except keyword lines at the same indentation level.

If it doesn’t find it, then it means the try-except operator hasn’t finished yet. Until the whole thing’s done, a line with a lower indentation level cannot appear. Here’s an example:

def multiply_by_two(x):
    try:
        return 2 * x
multiply_by_two(3)

This error is much less common and harder to find. Try must always have at least one except. If you don’t need to do anything on an exception, use the pass keyword.

def multiply_by_two(x):
    try:
        return 2 * x
    except:
        pass
multiply_by_two(3)
6

This isn’t great, but it is syntactically correct. 

Use accurate error definitions in your try-except statements, and don’t use empty excepts. If you’re trying to handle an exception, use at least BaseException.

Here’s more Python support:

  • 9 Examples of Unexpected Character After Line Continuation Character
  • 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed
  • How to Solve ‘Tuple’ Object Does Not Support Item Assignment
  • How to Solve SyntaxError: Invalid Character in Identifier
  • ImportError: Attempted Relative Import With No Known Parent Package

Are you looking for the solution of Python unexpected unindent error? This is one of the common python exceptions among developers. Let’s understand when it occurs? We will also see its solution in this article.

What is Python unexpected unindent exception?

Most of the python beginners face this problem. There are so many forms of Python unexpected unindent exception/error.  As most of the popular programming languages like Java, C, C + use curly braces to complete the program block. But Python programming language use indentation in the place of braces in program block.

Indentation in Python is nothing but the use of the white space according to the python syntax. If we make any mistake in python indentation, this Python unexpected unindent exception occurs.

Let’s know the cases of it.

Case 1: Improper use of white space

Here is the example of this indentation exception.

def fun_correct_Identation(): 
    print("I m learning Identation Exception") 
    print("correct Indentation ") 

fun_correct_Identation()

The above code sample demonstrates the correct use of Indentation in python.

correct Identation python

correct Identation python

Now we will know how the improper white space can generate IndentationError: unexpected indent. Let’s see the below example-

def fun_incorrect_Identation(): 
    print("I m learning Identation Exception") 
     print("incorrect Identation ")  

fun_incorrect_Identation()

Here is the error Exception for the above code.

Here we have used one extra white space.  For instance, This generates the above exception in the example.

unexpected indent python

unexpected indent python

Case 2: White space and Tab using Alternatively

White space and Tab have the almost same effect in plain text. But there is a huge difference in Python programming language.

Note –

  1. A conditional expression like if in python starts after a white space. If we do not provide proper spacing in that expression. This will again raise the Indentation Exception.
  2. Loop and so many codes blocks in python need proper spacing.

How to fix indentation error in python?

Most importantly, Using any IDE or python supportive text editor is really helpful in fixing indentation error in python. This IDE helps in clearly seeing the improper white space or incomplete code blocks. 

Thanks 

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Автор оригинала: Chris.

Если вы похожи на меня, вы сначала попробуйте все в своем коде и исправить ошибки, как они приходят. Одна частая ошибка в Python – IndentationError: неожиданный отступ Отказ Итак, что означает это сообщение об ошибке?

Ошибка . IndentationError: неожиданный отступ Возникает, если вы используете непоследовательную отступ вкладок или пробелы для блоков кода с отступом, таких как Если блок и для петля. Например, Python бросит ошибку вдавливания, если вы используете для петля с три персонажа пробелов Отступ для первой строки и Один символ вкладок отступ второй строки корпуса петли. Чтобы устранить ошибку, используйте одинаковое количество пустых пробелов для всех блоков кода с отступом.

Давайте посмотрим на пример, где возникает эта ошибка:

for i in range(10):
  print(i)
   print('--')

Первая строка в корпусе петли использует два пробела в качестве уровня вдавливания. Вторая строка в корпусе петлей использует три персонажа пробелов в качестве уровня отступа. Таким образом, блоки вдавливания различны для разных линий того же блока. Однако Python ожидает, что все линии с отступом имеют структурно те же отступ.

Чтобы исправить ошибку, просто используйте одинаковое количество пробелов для каждой строки кода:

for i in range(10):
    print(i)
    print('--')

Общая рекомендация состоит в том, чтобы использовать четыре единственных пробелных персонажей '' для каждого Отступ уровень. Если у вас вложенные уровни вдавливания, это означает, что второй уровень вдавливания имеет одновение пробелы:

for i in range(10):
    for j in range(10):
        print(i, j)

Смесительные вкладки и пробелы частоты часто вызывают ошибку

Общая проблема также в том, что вдавливание, по-видимому, является последовательным – пока это не так. Следующий код имеет один символ вкладки в первой строке и четырех пустых пробеле во второй строке блока кода с отступом. Они выглядят одинаково, но Python все еще бросает ошибку вдавливания.

На первый взгляд углубление выглядит одинаково. Однако, если вы пройдете пробелы перед Печать (I) , вы видите, что он состоит только из одного табличного характера, в то время как пробелы перед Распечатать (j) Заявление состоит из ряда пустых мест '' Отказ

Попробуйте сами: Прежде чем я скажу вам, что делать с этим, попробуйте исправить код себя в нашей интерактивной оболочке Python:

Упражнение : Исправьте код в оболочке интерактивного кода, чтобы избавиться от сообщения об ошибке.

Вы хотите развивать навыки Хорошо округлый Python Professional То же оплачивается в процессе? Станьте питоном фрилансером и закажите свою книгу Оставляя крысиную гонку с Python На Amazon ( Kindle/Print )!

Как исправить ошибку отступа на все времена?

Источник ошибки часто является неправильным использованием вкладок и пробеловных символов. Во многих редакторах кода вы можете установить символ вкладки на фиксированное количество символов пробела. Таким образом, вы, по сути никогда не используете сам табличный символ. Например, если у вас есть Sublime Text Editor, следующее быстрое руководство гарантирует, что вы никогда не будете работать в этой ошибке:

  • Установить Возвышенный текст Использовать вкладки для отступа: Вид -> Отступ -> Преобразовать вдавшиеся вкладки
  • Снимите флажок Опция Отступ с использованием пробелов в том же подменю выше.

Куда пойти отсюда?

Достаточно теории, давайте познакомимся!

Чтобы стать успешным в кодировке, вам нужно выйти туда и решать реальные проблемы для реальных людей. Вот как вы можете легко стать шестифункциональным тренером. И вот как вы польские навыки, которые вам действительно нужны на практике. В конце концов, что такое использование теории обучения, что никто никогда не нуждается?

Практические проекты – это то, как вы обостряете вашу пилу в кодировке!

Вы хотите стать мастером кода, сосредоточившись на практических кодовых проектах, которые фактически зарабатывают вам деньги и решают проблемы для людей?

Затем станьте питоном независимым разработчиком! Это лучший способ приближения к задаче улучшения ваших навыков Python – даже если вы являетесь полным новичком.

Присоединяйтесь к моему бесплатным вебинаре «Как создать свой навык высокого дохода Python» и посмотреть, как я вырос на моем кодированном бизнесе в Интернете и как вы можете, слишком от комфорта вашего собственного дома.

Присоединяйтесь к свободному вебинару сейчас!

Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.

Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python One-listers (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.

Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка unknown software exception 0xc0000094
  • Ошибка unarc isdone dll 100
  • Ошибка unexpected store extension
  • Ошибка unknown software exception 0x40000015

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии