Python-сообщество
SergeyAlekseevich$ python ex14.py rr rr
File “ex14.py”, line 24
lives = raw_input(prompt).decode(sys.stdin.encoding or locale.p=getpreferredencoding(True))
SyntaxError: keyword can’t be an expression
Air-Sergej:
SergeyAlekseevich$ python ex14.py fuck ff
File “ex14.py”, line 24
lives = raw_input(prompt).decode(sys.stdin.encoding or locale.p=getpreferredencoding(True))
SyntaxError: keyword can’t be an expression
Air-Sergej:
УЖЕ 3 ЧАСА НЕ МОГУ ЕЕ ИСПРАВИТЬ. Что я делаю не так?
Отредактировано FishHook (Сен. 15, 2017 20:06:14)
#2 Сен. 15, 2017 20:06:22
Помогите избавиться от ошибки: keyword can't be an expression
#3 Сен. 15, 2017 20:08:42
Помогите избавиться от ошибки: keyword can't be an expression
#4 Сен. 15, 2017 20:23:42
Помогите избавиться от ошибки: keyword can't be an expression
Так написано в книге Learn python the hard way
#5 Сен. 15, 2017 20:24:03
Помогите избавиться от ошибки: keyword can't be an expression
Чем можно его заменить чтобы код работал?
#6 Сен. 15, 2017 20:35:20
Помогите избавиться от ошибки: keyword can't be an expression
#7 Сен. 15, 2017 20:39:11
Помогите избавиться от ошибки: keyword can't be an expression
#8 Сен. 16, 2017 10:58:28
Помогите избавиться от ошибки: keyword can't be an expression
Я исправил ошибки и у меня все заработало, но не выводятся ответы пользователя на русском. (18 -20 строки) Нужно чтобы выводились ответы на русском а не: \xd0\xb2 \xd0\x9c…
SergeyAlekseevich$ python ex14.py sergey 15
Привет sergey, Я — сценарий ‘ex14.py’.
Я хочу задать тебе несколько вопросов.
Я тебе нравлюсь, sergey?
>ДА
Ты весишь ‘15’ кг!! Cколько тебе лет?
>23
Где ты живешь, sergey?
>в Москве
На каком компьютере ты работаешь?
>мак ос
Ты ответил ‘\xd0\x94\xd0\x90’ на вопрос, нравлюсь ли я тебе.# строка 18
Ты живешь в ‘\xd0\xb2 \xd0\x9c\xd0\xbe\xd1\x81\xd0\xba\xd0\xb2\xd0\xb5’. Не представляю, где это.
И в твои ‘23’, у тебя есть компьютер ‘\xd0\xbc\xd0\xb0\xd0\xba \xd0\xbe\xd1\x81’. Прекрасно!
from sys import argv
script, user_name, your_weight = argv
prompt = ‘>’
print u“Привет %s, Я — сценарий %r.” % (user_name, script)
print u“Я хочу задать тебе несколько вопросов.”
print u“Я тебе нравлюсь, %s?” % user_name
likes = raw_input(prompt)
print“ Ты весишь %r кг!! Cколько тебе лет?” % your_weight
ages = raw_input(prompt)
print u“Где ты живешь, %s?” % user_name
lives = raw_input(prompt)
print u“На каком компьютере ты работаешь?”
computer = raw_input(prompt)
print “”“Ты ответил %r на вопрос, нравлюсь ли я тебе.
Ты живешь в %r. Не представляю, где это.
И в твои %r, у тебя есть компьютер %r. Прекрасно!
”“” % (likes, lives, ages, computer)
Fix Keywords Cannot Be Expression Error in Python

Keywords are reserved words with a specific purpose, and keyword arguments in Python are values passed to a function identified using the parameter’s name.
We will get to know how to fix the keyword can’t be an expression in this article. It falls into SyntaxError in Python. A SyntaxError is raised when the basic syntax of Python is not followed.
This error is encountered in the following example.
In the above example, a is the keyword, and Hello is the argument value. We encounter the error because the keyword is an expression and has a dot ( .first ).
We can correct this by ensuring that the keyword is not in the form of an expression.
We usually get this error by performing simple operations related to passing values to a function. Take another example of this error while creating a dictionary using the dict() function.
See the code below.
While using the dict() constructor, the keys are passed as arguments, and they are interpreted as an expression by putting them in quotes. We can avoid this by removing the quotes in the keys.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
SyntaxError: keyword can't be an expression while creating a dictionary
How is this possible? According to Python type() name is a string:
Why is Python mixing up strings and expressions?
![]()
7 Answers 7
The problem with rack.session is that python thinks that you’re trying to use the value of expression rack.session and pass it to dict() , which is incorrect because dict() expects you to pass variables names when you’re using keyword arguments, these variables name are then converted to strings when the dict is created.
So, you can’t use an object on the left side of = , you can only use a valid identifier.
Byte code makes it even more clear what happens with rack.session :
So, with rack.session = val , python will think that you’re trying to use the value returned from rack.session and pass it to dict , which is incorrect. Secondly rack.session isn’t a valid identifier as dots( . ) are not allowed in python identifiers.
This is applicable to any function in python not even dict , a keyword argument must be a valid identifier.
![]()
As to «Why is Python mixing up strings and expressions?», it’s not. I’m not sure why you think python is doing this. You are mixing up strings and variables, which are quite different.
You should build a dictionary this way
![]()
The reason is that you give the dict this expression: rack.session=val , rather than a keyword.
Instead, you can get around this issue using dict(
The answer from Ashwini Chaudhary was quite good, but I can add more to clarify question.
The main reason why you’ve got this error is because your expression contain a point — ‘.’ symbol. And raising error directly say that: «keyword can’t be an expression».
This — ‘.’ symbol makes Python think, that current keyword name is not a valid name, but an expression, that you try to evaluate. Generally speaking you may pass as a key in dict() only valid name, from the point that such names could be a names for a variables dispite the fact that no variable evaluation actually can be happen here.
So your keys must contain only alphabeticals, digits, or underscore, and do not start with a digit (they must be valid Python identifiers as was said before).
For example these are not valid:
First, second and third are not valid, because they are expressions and because they are not valid identifiers, but fourth only because it is not a valid identifier.
To circumvent current limitations you may use one of the ways that was mentioned above, cause they accepting variable evaluation and if the key is the string, it can contain any characters:
SyntaxError: ключевое слово не может быть выражением при создании словаря
Как это возможно? По словам Питона type() имя это строка:
Почему Python смешивает строки и выражения?
6 ответов
Проблема с rack.session является то, что питон думает, что вы пытаетесь использовать значение выражения rack.session и передать его dict() , что неверно, потому что dict() ожидает, что вы передадите имена переменных, когда вы используете аргументы ключевых слов, эти имена переменных затем преобразуются в строки при создании dict.
Таким образом, вы не можете использовать объект на левой стороне = , вы можете использовать только действительный идентификатор.
Байт-код делает еще более понятным, что происходит с rack.session :
Итак, с rack.session = val , Python будет думать, что вы пытаетесь использовать значение, возвращаемое из rack.session и передать его dict , что неверно. во-вторых rack.session недопустимый идентификатор в виде точек ( . ) не допускаются в идентификаторах Python.
Это применимо к любой функции в Python, даже не dict , аргумент ключевого слова должен быть действительным идентификатором.
Что касается «Почему Python смешивает строки и выражения?», Это не так. Я не уверен, почему вы думаете, что Python делает это. Вы смешиваете строки и переменные, которые совершенно разные.
Причина в том, что вы даете dict это выражение: rack.session=val , а не ключевое слово.
Вместо этого вы можете обойти эту проблему, используя dict(
Ответ Ашвини Чаудхари был неплохим, но я могу добавить больше, чтобы прояснить вопрос.
Основная причина этой ошибки заключается в том, что ваше выражение содержит точку — ‘.’ символ. И при возникновении ошибки прямо говорится, что «ключевое слово не может быть выражением».
Эта — ‘.’ символ заставляет Python думать, что текущее имя ключевого слова не является допустимым именем, а выражением, которое вы пытаетесь оценить. Вообще говоря, вы можете передать в качестве ключа в dict() только действительное имя, с той точки зрения, что такие имена могут быть именами для переменных, несмотря на то, что здесь фактически не может быть никакой оценки переменных.
Таким образом, ваши ключи должны содержать только буквы, цифры или подчеркивания и не начинаться с цифры (они должны быть действительными идентификаторами Python, как было сказано ранее).
Например, они недействительны:
Первый, второй и третий недопустимы, потому что они являются выражениями и потому что они не являются действительными идентификаторами, а четвертый — только потому, что это недопустимый идентификатор.
Чтобы обойти текущие ограничения, вы можете использовать один из способов, упомянутых выше, потому что они принимают оценку переменных, и если ключ является строкой, она может содержать любые символы: