Small turtles 8.2 great condition thirds of after-school problem summary

2. Suppose x = 1, y = 2, z = 3, how quickly the exchange of the values of the three variables?
A: x, y, z = z , y, x

3. Guess (x <y and [x] or [y]) [0] realize what kind of function?
A: This is actually before Python is not a member of the ternary operator is Python, Python community of small partners to use and flexible to implement and or with the ternary operator functions, while there are involved here and the list of slices knowledge, this knowledge will soon be part of the explanation, friends can not wait a little preview below.

This equation can be simplified as (x <y and x or y ), i.e., x <y is true output x, otherwise the output y. But when the case is 0 (equivalent to the flase) x and y will misjudgment. Thus to [x] and [y], so that [x] and [y] are true on, plus (0), and becomes the first element of the list, i.e., restored to x or y.
Python general wording to x if x <y else y
so the code easier to understand.
#### PS: x <y is true, then the output true, true and [x] = x (short circuit principle), or x = x Y
x <Y is false, the output is false, false and [x] = false, false or the y-= the y-
4.4. Have you heard of the membership operator do?
A: Python has a membership operator: in, to check whether a value is in the sequence, if the sequence returns True, otherwise False.
## with a check sequence
, for example:

name = 'small turtles'
'fish' in name
True

'Oily fish' in name
False

  1. Python's author in a long time refused to join the ternary operator is afraid to come up with the C language, like garbage international competitions, egg pain complexity daunting for beginners, but once you figure out if ternary operator tips, perhaps some of the more complex problems but solved.
    The following code modified to achieve ternary operator:
x, y, z = 6, 5, 4
if x < y:
    small = x
    if z < small:
        small = z
elif y < z:
    small = y
else:
    small = z

answer:

个人答案:
x, y, z = 6, 5, 4
small=x if x < y and x<z else y<z and y or z
print (small)
#三元操作和and or 短路逻辑结合,不是纯正的三元

标准答案: 

small = x if (x < y and x < z) else (y if y < z else z)
#理解记忆:y if y<z else z 当中开头的y其实就是if条件成立时的结果,否则为z

Summary: and or not use flexible, short-circuit logic, ternary operator, in check




Published 17 original articles · won praise 1 · views 365

Guess you like

Origin blog.csdn.net/cccccccaaaaaaaaa/article/details/105183153