python学习十二天

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值