一、逻辑运算符号
主要涉及到==、and、or、not四个逻辑运算符号
1、逻辑相等(==)
仅当p或q包含的值相同的时候,即都为True或都为False的时候,表达式p==q的结果才为True.表达式p!=q检验p和q是否不同,仅在p和q在不同的时候,才返回True.
>>> False==True
False
>>> True==False
False
>>> True==True
True
>>> False!=False
False
>>> True!=False
True
>>> True!=True
False
2、逻辑与(and)
当p和q同时都True时候,才为True,其他情况都为False
>>> False and False
False
>>> False and True
False
>>> True and True
True
>>> True and False
False
3、逻辑或(or)
仅当p和q至少有一个为True的时候,p or q 才为True.
>>> False or False
False
>>> False or True
True
>>> True or False
True
>>> True or True
True
4、逻辑非(not)
在P为False的时,表达式 not p为True;在p为True时,not p为False
>>> not True
False
>>> not False
True
二、条件语句
1、if语句
if条件判断语句,后面需要加入一个冒号(:)
例如:
#if.py
password=input('what is your name?')
if password=='intely':
print('please logging on ...')
else:
print('Incorrect password.')
print('All done.')
结果是:
>>>
what is your name?intely
please logging on ...
All done.
程序理解是:如果输入的password为intely,则进行登陆;否则就退出。然后最后一条信息就是输出All done.
2、if/elif语句
if/elif语句则是if语句的推广版本,包含多个条件,如某游乐园提供儿童优惠价:不超过3岁则免费;4~15岁儿童打折;15岁以上的与大人同价。程序如下:
#elif
age=int(input('How old are you?'))
if age<=3:
print('free')
elif age>3 and age<15:
print('child fare')
else:
print('adult fare')
结果如下:
>>>
How old are you?4
child fare