Syntaxerror multiple statements found while compiling a single statement что значит

Русские Блоги

Сообщение об ошибке

Я столкнулся с этой ошибкой при написании Python в Win10 и выполнении нескольких строк кода в IDLE.

Решение

да Поместите несколько строк кода в один файл Выполнить

Конкретные шаги

Интеллектуальная рекомендация

[Leetcode Tour] Array-697. Степень массива

Syntaxerror multiple statements found while compiling a single statement что значит. Смотреть фото Syntaxerror multiple statements found while compiling a single statement что значит. Смотреть картинку Syntaxerror multiple statements found while compiling a single statement что значит. Картинка про Syntaxerror multiple statements found while compiling a single statement что значит. Фото Syntaxerror multiple statements found while compiling a single statement что значит

Добавить расширение Redis для PHP7 под Windows

1 Просмотр информации о версии PHP Непосредственно используйте функцию phpinfo (), вывод в браузер в порядке Результаты вывода, в основном, отображают следующую информацию: версия PHP, архитектура, сб.

неправильная причина: Первичный ключ сущности установлен в режим саморазвития, но первичный ключ идентификатора устанавливается для него при сохранении.

Syntaxerror multiple statements found while compiling a single statement что значит. Смотреть фото Syntaxerror multiple statements found while compiling a single statement что значит. Смотреть картинку Syntaxerror multiple statements found while compiling a single statement что значит. Картинка про Syntaxerror multiple statements found while compiling a single statement что значит. Фото Syntaxerror multiple statements found while compiling a single statement что значит

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

Syntaxerror multiple statements found while compiling a single statement что значит. Смотреть фото Syntaxerror multiple statements found while compiling a single statement что значит. Смотреть картинку Syntaxerror multiple statements found while compiling a single statement что значит. Картинка про Syntaxerror multiple statements found while compiling a single statement что значит. Фото Syntaxerror multiple statements found while compiling a single statement что значит

Том Зибель технические книги рекомендуется

iOS разработка программного обеспечения 1. Опытный в Objective-C [США] Кит Ли, Су Баолонг Народная почта и телекоммуникационная пресса Эта книга подходит для некоторых разработчиков, которые уже начал.

Источник

Python-сообщество

Уведомления

#1 Апрель 4, 2018 16:36:19

SyntaxError: multiple statements found while compiling a single statement

Только начал работать с питоном, но выдает такую ошибку.
Подскажите в чем проблема.

Отредактировано Dwarf_DH_58_LVL (Апрель 4, 2018 17:50:34)

#2 Апрель 4, 2018 16:48:54

SyntaxError: multiple statements found while compiling a single statement

код нужно постить в специальных тегах code

_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com

#3 Апрель 4, 2018 18:31:08

SyntaxError: multiple statements found while compiling a single statement

1. попробуйте выполнить одну строку:

#4 Апрель 4, 2018 20:32:28

SyntaxError: multiple statements found while compiling a single statement

Отредактировано spikejke (Апрель 4, 2018 20:35:36)

#5 Апрель 4, 2018 22:09:46

SyntaxError: multiple statements found while compiling a single statement

spikejke, я задавал вопросы не форуму, а ТС в качестве намёка где искать ошибки. Если он на них ответит, то сможет исправить ошибки.

#6 Апрель 5, 2018 05:28:21

SyntaxError: multiple statements found while compiling a single statement

rami
spikejke, я задавал вопросы не форуму, а ТС в качестве намёка где искать ошибки. Если он на них ответит, то сможет исправить ошибки.

Источник

Multiple statements found while compiling a single statement [duplicate]

I am brand new to programming. I am using the Dive into Python book and am trying to run the first example, humansize.py. I have copied and pasted the code into Idle, the Python shell and keep coming up with the same syntax error: «multiple statements found while compiling a single statement.»

I am downloading the code into BBEdit and then copying and pasting it into Idle. I have looked online and people said it could be a tab versus space issue. But I’ve went through the code and it looks identical to the book, I’ve even deleted and reinserted 4 spaces in all the lines of code and I’m still getting the error.

It’s frustrating because I am sure that it’s a simple issue but I’ve done everything that I know of, (in terms of trying to research the problem) to get it to work. If it is a space versus tabs issue, do any of you know where I can go and learn how to do the process of copying and entering code into Idle properly? I am a TRUE beginner.

I’d appreciate any assistance from the community. Thank you!

1 Answer 1

You have a few indentation problems. In python indentation is very important, because the interpreter uses indentation levels to decide how to group statements. for example:

The statement(s) grouped with the if (False) statement should never be ran because if (False) should never be true. But the example I gave you will still output «World». This is because the interpreter doesn’t see the second print statement as being a part of the if statement. Now if I were to take the exact same code and indent the second print statement like so:

The interpreter will see that both print statements are one indentation level deeper than the if statement and nothing will be outputted because if (False) is always false.

The same indentation applies to function definitions. For example:

Because the if statement is indented one level deeper that the definition of foo it is grouped with the foo function. So when you call the foo function it will output «Hello, World».

Now for variables. In your code you have the variable indented in one level. Which would be fine if it were a part of a function definition, if statement, for loop, etc. But since it isn’t, it creates problems. Take the following for example:

Will give you a syntax or indentation error, While:

Will print «Hello, World».

Now to focus on your code:

Needs to be un-indented one level to become:

Needs to be un-indented one level to become:

Источник

SyntaxError: multiple statements found while compiling a single statement #6

Comments

Mtaylor777 commented May 29, 2017

Just bought book, first day of programming. «Hello World» worked fine, but every time I type something more complex, I get the «SyntaxError: multiple statements found while compiling a single statement». Have tried copying and pasting from website and still get this error. Please help.

home = «America»
if home == «America»:
print(«Hello, America!»)
else:
print(«Hello, World!»)

SyntaxError: multiple statements found while compiling a single statement

The text was updated successfully, but these errors were encountered:

calthoff commented Jun 1, 2017

@Mtaylor777 Hey there. It looks like you are copying and pasting code into the shell, which you cannot do. You need to paste it into IDLE.

ZeezyW commented Jun 16, 2017 •

I am having this same issue, but it is not due to copy and pasting. Any time I enter code into the shell that is more than one command (sorry for the beginner terminology) I get this error. For example:

colors = [«purple», «orange», «green»]

guess = input(«Guess a color:»)

if guess in colors:
print(«You guessed correctly!»)
else:
print(«Wrong! Try again.»)

I can enter the «colors» line on it’s own, or i can enter the «guess» line on its own, but when I try to do both at the same time, or add the if clause to the end. I get this error. It looks to me as if I’m following the spacing in the book.

Источник

Несколько операторов, найденных при компиляции одного оператора

Я новичок в программировании. Я использую Dive в книгу Python и пытаюсь запустить первый пример, manize.py. Я скопировал и вставил код в Idle, оболочку Python и продолжал приходить с той же синтаксической ошибкой: “несколько операторов найдены при компиляции одного оператора”.

Я загружаю код в BBEdit, а затем копирую и вставляя его в Idle. Я посмотрел онлайн, и люди сказали, что это может быть проблема с вкладкой или пробелом. Но я просмотрел код, и он выглядит идентично книге, я даже удалил и ввел 4 пробела во всех строках кода, и я все еще получаю ошибку.

Это разочаровывает, потому что я уверен, что это простая проблема, но я сделал все, о чем я знаю (с точки зрения попытки исследования проблемы), чтобы заставить ее работать. Если это проблема с пробелами или вкладками, знаете ли вы, где я могу пойти, и научиться правильно выполнять процесс копирования и ввода кода в Idle? Я ИСТИННЫЙ новичок.

Буду признателен за любую помощь со стороны сообщества. Спасибо!

Я запускаю Mac OSX – V.10.7.5. Я использую последнюю версию Dive в книге Python и Python 3.3.

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

Оператор (ы), сгруппированный с оператором if (False), никогда не должен запускаться, потому что если (False) никогда не должно быть истинным. Но пример, который я вам дал, все равно выведет “Мир”. Это связано с тем, что интерпретатор не видит, что второй оператор печати является частью оператора if. Теперь, если бы я взял тот же самый код и отступом второй оператор печати так:

Интерпретатор увидит, что оба оператора печати – это один уровень отступов, глубже, чем оператор if, и ничего не будет выводиться, потому что если (False) всегда false.

Такой же отступ применяется к определениям функций. Например:

Поскольку оператор if имеет отступы на один уровень глубже, то определение foo сгруппировано с функцией foo. Поэтому, когда вы вызываете функцию foo, она выдает “Hello, World”.

Теперь для переменных. В вашем коде вы имеете переменную с отступом на одном уровне. Что было бы хорошо, если бы это было частью определения функции, если оператор, для цикла и т.д. Но поскольку это не так, это создает проблемы. Возьмем, например, следующее:

Дает вам синтаксическую или отступы, пока:

Будет напечатан “Hello, World”.

Теперь, чтобы сосредоточиться на вашем коде:

Требуется, чтобы один уровень не был отступом:

Требуется, чтобы один уровень не был отступом:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *