布尔值,比较运算符和布尔操作符
(一)布尔值(Boolean Values)
整数,浮点数和字符串有很多种不确定的值,但是布尔值只有两种:True和False
>>>spam=True
>>>spam
True
>>>True = 2+2
SyntaxError: assignment to keyword
(二)比较运算符(Comparison Operators)
| Opetator | Meaning |
| == | Equal to |
| != | Not equal to |
| < | Less than |
| > | Greater than |
| <= | Less than or equal to |
| >= | Greater than or equal to |
注意:
== 和!=可以用于任意的数据类型,但<,>和<=和>=只能用于整数和浮点值
>>>42 == 42
True
>>>42 == 99
False
>>>2!=3
True
>>> 'hello' == 'hello'
True
>>>'dog' != 'cat'
True
>>>42 == 42.0
True
(三)布尔操作符(Boolen Operators)
有三种布尔操作符:and,or和not
1)二元布尔运算符(Binary Boolean Operators)
and和or操作符总是适用于两个布尔值或表达式
Expression Evaluates to ...
True and True True
True and False False
False and True False
false and False False
True or True True
True or False True
False or True True
false or False False
>>>(4<5)and (5<6)
True
>>>(1==2)or (2==2)
True

2)The not operator
not操作符仅仅需要一个布尔值或表达式
>>>not True
False
>>>not not not not True
True
3)break和continue
1.break 跳出整个循环,而continue跳出本次循环;
2.continue语句告诉python跳出当前循环,进入下一个循环;
3.break语句用户终止循环语句;
4.break和continue语句用在while和for循环中。
1 while True: 2 name = input("Who are you?") 3 if name != 'sara': 4 continue 5 print('Hello, Joe. What is the password? (It is a fish.)') 6 password = input("Please input your password?") 7 if password == 'swordfish': 8 break 9 print("Access granted")
有一些其他数据类型的值,条件会考虑等效为True和False,当使用条件0,0.0和‘ ’(空的字符串)时,考虑为False,然而其他的值考虑为True
1 name = '' 2 while not name: 3 name = input("Enter your name:") 4 print('How many guests will you have?') 5 numOfGuests = int(input()) 6 if numOfGuests: 7 print('Be sure to have enough room for guests') 8 print('Done')
浙公网安备 33010602011771号