Câu hỏi phỏng vấn Python
Câu hỏi

What does an x = y or z assignment do in Python?

Câu trả lời

In Python, the expression x = y or z is an example of using the logical or operator in an assignment. This operator evaluates the operands from left to right and returns the first operand that evaluates to True in a boolean context, or the last operand if none are True.

Here's how it works step-by-step:

  1. Evaluate y: Python first evaluates the operand y. If y is truthy (i.e., it evaluates to True in a boolean context), then y becomes the value of x.
  2. Evaluate z (if necessary): If y is falsy (i.e., it evaluates to False in a boolean context), Python then evaluates z. Regardless of whether z is truthy or falsy, its value is assigned to x because it's the last operand evaluated.

This means that x will be assigned the value of y if y is truthy. If y is falsy, x will be assigned the value of z. This behavior makes x = y or z a useful shorthand for conditional assignments where you want to assign a default value (z) if the primary value (y) is co...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What does the Python nonlocal statement do (in Python 3.0 and later)?

senior

Why are default values shared between objects?

junior

What are local variables and global variables in Python?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào