1.if
缩进
#严格缩进
if g==1: #if后面有一个空格,还有冒号
print("right")
#没空格有()也行
if(g==1): #冒号
print("right")
判断条件也可以直接写True
if True: #冒号
print("right")
判断条件为数字:非零值视为True,零值视为False。
if 1:
print('1')
if 100:
print('100')
if 0:
print('0')
if -1:
print('-1')
输出:
'''
1
100
-1
'''
2.if else
>>> a = 1
>>> b = 2
>>> if a<=b:
... print('a小于等于b')
... else:
... print('a大于b')
...
a小于b
3.if elif if
>>> a = 1
>>> b = 2
>>> if a<b:
... print('a小于b')
... elif a>b:
... print('a大于b')
... else:
... print('a等于b')
a小于b
4.条件组合保留字:
#例1:
if not True:
print("即Fasle,不输出")
else:
print("输出")
#例2:
guess=1000
if guess>0 and guess<100:
print("right")
else:
print("wrong")
#<=、>=可以使用
if guess>=0:
print("ok")
三元运算符
>>> a = 1
>>> b = 2
>>> a if a<b else b
1
>>> print('a=%d' %a) if a<b else b
a=1
二.循环结构
计算1+2+3+…+99+100的结果:
>>> s=0
>>> for i in range(1,101):
... s+=i
... else: #else是循环结束的奖励
... print(s)
...
5050
>>> s=i=0
>>> while i<=100:
... s+=i
... i+=1
... else:
... print(s)
...
5050
#无变量for循环
for _ in range(10):
print("0")
循环控制保留字break和continue
while True:
name = input("entre your name :")
if name == "stop":
break
age = input("entre your age:")
print("your name is %s ,your age is %s" %(name,age) )
运行结果:
entre your name :lixiang
entre your age:18
your name is lixiang ,your age is 18
entre your name :stop
x = 10
while x:
x = x -1
if x % 2 != 0 :
continue
print(x)
运行结果:
8
6
4
2
0
pass语句
pass 不做任何事情,一般用做占位语句。
for i in range(10):
print(i)
pass
print("done")
'''
0
1
2
3
4
5
6
7
8
9
done
'''