五. Booleans and Conditionals
Using booleans for branching logic
x = True
print(x)
print(type(x))
'''
True
<class 'bool'>
'''
①Booleans
Python has a type bool which can take on one of two values: True and False.
②Comparison Operations
a == b, and, or, not等等
Python的逻辑运算返回值(或运算结果)为布尔代数形式
3.0 == 3
True
'3' == 3
False
①Python provides operators to combine boolean values using the standard concepts of “and”, “or”, and “not”.
def can_run_for_president(age, is_natural_born_citizen):
"""Can someone of the given age and citizenship status run for president in the US?"""
# The US Constitution says you must be a natural born citizen *and* at least 35 years old
return is_natural_born_citizen and (age >= 35)
print(can_run_for_president(19, True))
print(can_run_for_president(55, False))
print(can_run_for_president(55, True))
"""
The result is:
False
False
True
"""
②"and", “or”, and "not"有运算优先级
not>and>or
【为了防止记错可以用括号】
True or True and False
"""
The result is:
True
"""
③当逻辑关系比较复杂时,可以分层写
prepared_for_weather = have_umbrella or ((rain_level < 5) and have_hood) or (not (rain_level > 0 and is_workday))
prepared_for_weather = (
have_umbrella
or ((rain_level < 5) and have_hood)
or (not (rain_level > 0 and is_workday))
)
Conditionals(条件语句)
if, elif(新), and else.
【记得加冒号 : 以及加缩进】
除了else, 其他有判断条件
Note especially the use of colons ( : ) and whitespace to denote separate blocks of code. This is similar to what happens when we define a function - the function header ends with :, and the following line is indented with 4 spaces. All subsequent indented lines belong to the body of the function, until we encounter an unindented line, ending the function definition.
def inspect(x):
if x == 0:
print(x, "is zero")
elif x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is unlike anything I've ever seen...")
inspect(0)
inspect(-15)
"""
The result is:
0 is zero
-15 is negative
"""
之前有int(), float()
现在有Boolean conversion bool()
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"
"""
True
False
True
False
"""
if else语句两种写法
def quiz_message(grade):
if grade < 50:
outcome = 'failed'
else:
outcome = 'passed'
print('You', outcome, 'the quiz with a grade of', grade)
def quiz_message(grade):
outcome = 'failed' if grade < 50 else 'passed'
#逻辑运算outcome = ('failed' if grade < 50 else 'passed')
#相当于c语言中的outcome = grade < 50 ? 'failed' : 'passed'
print('You', outcome, 'the quiz with a grade of', grade)
六. Exercise: Booleans and Conditionals
略
七. Lists
Lists and the things you can do with them. Includes indexing, slicing and mutating
类似复合的数组,可以有数字,字符串,甚至函数等
my_favourite_things = [32, 'raindrops on roses', help]
my_favourite_things[0]
#和数组一样 从0数起
32
my_favourite_things[2]
#Type help() for interactive help, or help(object) for help about object.
my_favourite_things[-1]
#Type help() for interactive help, or help(object) for help about object.
#数组序号可用负数, -1即为离0最远的元素, -2即为次远
二维数组两种写法
hands = [
['J', 'Q', 'K'],
['2', '2', '2'],
['6', 'A', 'K'], # (Comma after the last element is optional)
]
# (I could also have written this on one line, but it can get hard to read)
hands = [['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K']]
Slicing 跟matlab中一样, 求得数组的某行某列至某行某列
此处的冒号 : 即有 “到” 的意思
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planets[0:3]
['Mercury', 'Venus', 'Earth']
planets[:3]
['Mercury', 'Venus', 'Earth']
#planets[0:3] is our way of asking for the elements of planets starting from index 0
#and continuing up to but not including index 3.可以理解为左闭右开[m,n)
planets[3:]
['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
# The last 3 planets
planets[-3:]
['Saturn', 'Uranus', 'Neptune']