条件判断:
当我们开始编写一个程序时,肯定会遇到要求程序能根据不同的条件做出相应的动作,这时我们就需要使用计算机语言的最基本的逻辑控制if.else语句来实现了
Python 中的if 语句由三部分组成,关键字本身,用于判断结果真假的条件表达式,以及当表达式为真或者非零时执行的码块。
1:格式如下:
if expression:
expr_true_suite
if 语句的expr_true_suite代码块只有在条件表达式为真时才执行,否则将继续执行紧跟在该代码块后面的语句
多重表达式
单个if语句可以通过使用布尔操作符and,or 和not 实现多重判断条件或是否来定判断条件:
if a > b and a < c : a = a+1
2:else语句
双重if 语句中当if 语句的表达式的结果为假,那么程序将执行else语句的代码,语法如下:
if expression:
expr_true_suite
else:
expr_true_suite
3: elif语句
当检查多个值时,我们就需要用elif语句了,elif 可以有多个,else只能有一个。
if expression:
expr_true_suite
elif expression1:
expr_true_suite1
elif expressionN:
expr_true_suiteN
......
else:
expr_true_suite
成绩的例子:
s= int(input("please your score: "))
if s> 90:
print("你是优等生")
elif 80 < s< 90:
print("你是上等生")
elif 60 < s< 80:
print("继续加油,你优势不大")
else:
print("你不及格")
二:循环语句
While语句中的代码会一直执行,直到循环条件不再为真。
while expression:
expr_true_suite
例如:
i = 0
while i < 10:
i = i+1
print(i)
无限循环:当使用while True时,表明条件一直为真,这样程序会一直执行下去,在实际生产当中,while语句一定要小心利用。
另外,while 也支持else语句
例子:上在的if 语句我们只允许用户输入三次,三次后自动退出
i = 0
while i < 3:
s = int(input("please your score: "))
if s > 90:
print("你是优等生")
elif 80 < s < 90:
print("你是上等生")
elif 60 < s < 80:
print("继续加油,你优势不大")
else:
print("你不及格")
i = i+1
三:for 循环
for 语句是另一种循环机制的实现方法,可以用来遍历序列成员,可以用在列表解析和生成器表达式中,它会自动的调用迭代器的next()方法,捕获异常并结束循环,for 语句依然支持else语句
1:一般的使用方法:
for i in iterable: print(i)
例子:
针对序列
for i in "name":
print("i:",i)
### 输出 结果
i: n
i: a
i: m
i: e
针对列表:
l = ['my','name','is',]
for i in l:
print("i:",i)
### 输出 结果
i: my
i: name
i: is
四:break 语句
break 语句可以结束当前循环然后跳转到下条语句,
t = 10
while t>0:
print("t 的值是 %d" % int(t))
t= t-1
if t== 5:
break ### 结束当前循环执行下一条语句
print("再见")
###输出结果
t的值 是10
t的值 是9
t的值 是8
t的值 是7
t的值 是6
再见
五:continue语句
Continue 用来跳出本次循环,继续下一次循环,
t = 10
while t >0:
t = t -1
if t == 5:
# print("t 的值 是 %d" % int(t))
continue
print("t %d 再见"%t)
###输出结果
t 9 再见
t 8 再见
t 7 再见
t 6 再见
t 4 再见
t 3 再见
t 2 再见
t 1 再见
t 0 再见
六:pass语句
有些地方在语法上要求必须有代码,而我们又真的在这个地主不做操作时怎么办,有些人直接尝试不写任何语句,结果发现程序报错了,python 为我们提供了pass语句,它的功能就是不做任何事情,
例如我们修改前面的成绩脚本,当在60以上时不做任何操作
i = 0
while i <3:
s = int(input("please your score: "))
if s > 90:
#print("你是优等生")
pass
elif 80 <s < 90:
#print("你是上等生")
pass
elif 60 <s < 80:
#print("继续加油,你优势不大")
pass
else:
print("你不及格")
i = i+1