程序员

python的选择结构

2018-04-10  本文已影响29人  知识学者

python的逻辑运算符:and(逻辑与),or(逻辑或),not(逻辑非).
和其它语言与[&&],或[||],非[!]不一样,感觉有些怪。

>>> not 0
True
>>> not ''
True
>>> not ' '
False
>>> 1+True
2

判断闰年

(year%4==0 and year%100!=0) or  year%400==0

判断字母

(ch>='a' and ch<='z') or ( ch>='a' and ch<='z')

逻辑运算具有短路的性质,可以进行一些操作,在shell命令中,或者替代一些if语句

>>> 2>3 and 8>6
False
>>> 22 or 1+1!=2
22
>>> 1+1!=2
False
>>> 22 and '333'
'333'

测试运算
in运算符用于在指定的序列中查找某一值,存在返回True,否则False.

>>> 6 in [1,2,6]
True
>>> a=(1,2,3)
>>> 1 in a
True
>>> 2 not in a
False

身份测试
身份测试用于测试二个变量是否指向同一个对象。

>>> a=68
>>> b=68
>>> c=66
>>> a is b
True
>>> a is not c
True

选择结构

单分直格式:

if 条件表达式:
    语句块。

双分支结构
格式:

if 条件表达式:
    语句块1
else:
    语句块2
if (1+1==2):
    print('yes')
yes

条件表达式后面的语句块必须向右缩进,默认4个空格,类似其它语言的 { },其它比如for语句,def等都需要缩进,注意一下就行了。

a,b=eval(input("put into a,b"))
if(a>b):
    max=a
else:
    max=b
print('max={0}'.format(max))
put into a,b6,8
max=8

多分支语句

if 条件表达式1:
    语句块1
elif 条件表达式2:
    语句块2
elif 条件表达式3:
   语句块3
[else:
    语句块n]

上一篇 下一篇

猜你喜欢

热点阅读