b = False if b: print('b是True') else: print('b是False') n = 0 if n: print('n不是零值') else: print('n是零值') s = "" if s: print('s不是空字符串') else: print('s是空字符串') l = [] if l: print('l不是空列表') else: print('l是空列表') d = {} if d: print('d不是空字典') else: print('d是空字典')
#不规定时默认函数返还None deffunc(): print("函数被调用") if func(): print('func()返回值不是空') else: print('func()返回值为空')
age = int( input("请输入你的年龄:") ) if age < 12 : print("婴幼儿") elif age >= 12and age < 18: print("青少年") elif age >= 18and age < 30: print("成年人") elif age >= 30and age < 50: #TODO: 成年人 else: print("老年人")
age = int( input("请输入你的年龄:") ) if age < 12 : print("婴幼儿") elif age >= 12and age < 18: print("青少年") elif age >= 18and age < 30: print("成年人") elif age >= 30and age < 50: pass else: print("老年人")
my_char="http://c.biancheng.net/python/" i = 0; while i<len(my_char): print(my_char[i],end="") i = i + 1
运行结果:
1
http://c.biancheng.net/python/
只需要保证while在有限次循环以后能够退出就行,同时循环体内部的代码缩进要相同。
Python for循环及用法详解
1 2 3 4
for 迭代变量 in 字符串|列表|元组|字典|集合: 代码块 for 索引值,元素 in 枚举: 代码块
1 2 3 4 5
my_dic = {'python教程':"http://c.biancheng.net/python/",\ 'shell教程':"http://c.biancheng.net/shell/",\ 'java教程':"http://c.biancheng.net/java/"} for ele in my_dic: print('ele =', ele)
data = [5,8,4,1] #实现冒泡排序 for i inrange(len(data)-1): for j inrange(len(data)-i-1): if(data[j]>data[j+1]): data[j],data[j+1] = data[j+1],data[j] print("排序后:",data)
add = "http://c.biancheng.net/python/,http://c.biancheng.net/shell/" for i in add: if i == ',' : #终止循环 break print(i,end="") else: print("执行 else 语句中的代码") print("\n执行循环体外的代码")
my_list = [11,12,13] my_tuple = (21,22,23) print([x for x inzip(my_list,my_tuple)]) my_dic = {31:2,32:4,33:5} my_set = {41,42,43,44} print([x for x inzip(my_dic)]) my_pychar = "python" my_shechar = "shell" print([x for x inzip(my_pychar,my_shechar)])
#将列表进行逆序 print([x for x inreversed([1,2,3,4,5])]) #将元组进行逆序 print([x for x inreversed((1,2,3,4,5))]) #将字符串进行逆序 print([x for x inreversed("abcdefg")]) #将 range() 生成的区间列表进行逆序 print([x for x inreversed(range(10))])