Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Python%20Interview%20Questions%20and%20Answers

Question: Why can't I use an assignment in an expression?
Answer:

Many people used to C or Perl complain that they want to use this C idiom:

while (line = readline(f)) {
  ...do something with line...
}

 
where in Python you're forced to write this:

while True:
  line = f.readline() if not line:
  break
...do something with line...

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:

 
if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}

 
The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.

 
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.

Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook