flag =False
name ='luren'if name =='python':# 判断变量否为'python'
flag =True# 条件成立时设置标志为真print('welcome boss')# 并输出欢迎信息else:print(name)# 条件不成立时输出变量名称=====================
luren
多种条件判断:if-elif-…-else
# 多种条件判断:if-elif-...-else
num =2if num ==3:# 判断num的值print('boss')elif num ==2:print('user')elif num ==1:print('worker')elif num <0:# 值小于零时输出print('error')else:print('roadman')# 条件均不成立时输出================
user
单语句多条件判断:or and
# 单语句多条件判断:or and
num =5if num >=0and num <=10:print('hello')# 判断值是否在0~10之间# 输出结果: hello
num =10if num <0or num >10:print('hello')else:print('undefine')# 判断值是否在小于0或大于10# 输出结果: undefine
num =8if(num >=0and num <=5)or(num >=10and num <=15):print('hello')else:print('undefine')# 判断值是否在0~5或者10~15之间# 输出结果: undefine===========================
hello
undefine
undefine
# 通过for遍历序列、映射
lst =list(range(10))for i in lst[::2]:print(i)print('-----')# 遍历list
age ={'Tom':18,'Jack':19,'Alex':17,'Mary':20}for name in age:print(name +'年龄为:%s岁'% age[name])# 遍历字典================02468-----
Mary年龄为:20岁
Tom年龄为:18岁
Alex年龄为:17岁
Jack年龄为:19岁
嵌套循环
# 嵌套循环for i inrange(3):for j inrange(2):print(i,j)# 循环套循环,注意:尽量不要多于3个嵌套============000110112021
while循环
执行语句可以是单个语句或语句块
判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。
当判断条件假false时,循环结束。
基本运行逻辑
# 基本运行逻辑
count =0while count <9:print('The count is:', count)
count = count +1print("Good bye!")# 这里count<9是一个判断语句,当判断为True时,则继续运行=========================
The count is:0
The count is:1
The count is:2
The count is:3
The count is:4
The count is:5
The count is:6
The count is:7
The count is:8
Good bye!
关于无限循环
# 关于无限循环:如果条件判断语句永远为 true,循环将会无限的执行下去
var =1while var ==1:
num =input("Enter a number :")print("You entered: ", num)print("Good bye!")# 该条件永远为true,循环将无限执行下去# 一定要避免无限循环!!
while-else语句
# while-else语句
count =0while count <5:print(count," is less than 5")
count = count +1else:print(count," is not less than 5")# 逻辑和if-else一样================0is less than 51is less than 52is less than 53is less than 54is less than 55isnot less than 5
循环控制语句
break语句
# break语句
s =0
n =1while n >0:
s = s + n
n = n +1if n ==20:breakprint(s)# break语句用来终止循环语句,即便循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。
s =0for i inrange(10):for j inrange(5):
s = s +(i*j)print('第%i次计算'%(i+j))if s >20:breakprint('结果为%i'% s)# 如果使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码。=================190
第0次计算
第1次计算
第2次计算
第3次计算
第4次计算
第1次计算
第2次计算
第3次计算
第4次计算
第5次计算
第2次计算
第3次计算
第4次计算
第5次计算
第6次计算
结果为30
continue语句
# continue语句
s =0for i inrange(50):if i%2==0:
s += i
else:continueprint('第%i次计算'%(i/2))print('结果为%i'% s)# continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。==================
第0次计算
第1次计算
第2次计算
第3次计算
第4次计算
第5次计算
第6次计算
第7次计算
第8次计算
第9次计算
第10次计算
第11次计算
第12次计算
第13次计算
第14次计算
第15次计算
第16次计算
第17次计算
第18次计算
第19次计算
第20次计算
第21次计算
第22次计算
第23次计算
第24次计算
结果为600
pass语句
# pass语句for letter in'Python':if letter =='h':passprint('当前字母 : h,但是我pass了')print('当前字母 :', letter)print("Good bye!")# pass是空语句,是为了保持程序结构的完整性。(不中断也不跳过)============================
当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h,但是我pass了
当前字母 : h
当前字母 : o
当前字母 : n
Good bye!