https://www.kaggle.com/code/colinmorris/booleans-and-conditionals/tutorial
Booleans
Remember to use == instead of = when making comparisons. If you write n == 2 you are asking about the value of n. When you write n = 2 you are changing the value of n.
记得之前有学到一个编程技巧,当写判断语句时,如n2,写成2n,以此可避免将其写成赋值,因为2=n会报错
if x == 0:
print(x, "is zero")
print("Splitting", total_candies, "candies")
默认执行优先级not、and、or
Conditionals
print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))
# Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples)
# are "falsey" and the rest are "truthy"
if 0:
print(0)
elif "spam":
print("spam")
This condition would be pretty complicated to express using just and, or and not, but using boolean-to-integer conversion gives us this short solution:
return (int(ketchup) + int(mustard) + int(onion)) == 1
Fun fact: we don’t technically need to call int on the arguments. Just by doing addition with booleans, Python implicitly does the integer conversion. So we could also write…
return (ketchup + mustard + onion) == 1
Lists&Tuples
a = [1, 2, 3]
b = [1, [2, 3]]
c = []
d = [1, 2, 3][1:] #与b相同
squares = [n**2 for n in range(10)]
squares = []
for n in range(10):
squares.append(n**2)
short_planets = [planet for planet in planets if len(planet) < 6]
Strings and Dictionaries
https://www.kaggle.com/code/colinmorris/strings-and-dictionaries
print("Pluto's a planet!")
print('My dog is named "Pluto"')
[char+'! ' for char in planet]
"{}, you'll always be the {}th planet to me.".format(planet, position)
So much cleaner! We call .format() on a “format string”, where the Python values we want to insert are represented with {} placeholders.