while 循环
‘‘‘
1、什么是循环?
循环即重复的过程
2、为什么要有循环
3、while循环的语法(又称之为条件循环)
while 条件:
代码1
代码2
代码3
。。。。
‘‘‘
# 注意:下述形式的死循环,会造成cpu的占用率过高
# i=1
# while True:
# i+=1
#打印1-10
# n=1
# while True:
# if n <= 10: #n=10
# print(n)
# n+=1
# else:
# break
#打印1-10:改进1
# n=1
# while True:
# if n > 10:break
# print(n)
# n+=1
#打印1-10:改进2
# n=1
# while n <= 10:
# print(n) #n=10
# n+=1 #n=11
# while True:
# name=input(‘please input your name: ‘)
# pwd=input(‘please input your password: ‘)
# if name == ‘egon‘ and pwd == ‘123‘:
# print(‘登录成功‘)
# else:
# print(‘用户名或密码错误‘)
#4 while+break:break的意思是结束本层循环
# while True:
# name=input(‘please input your name: ‘)
# pwd=input(‘please input your password: ‘)
# if name == ‘egon‘ and pwd == ‘123‘:
# print(‘登录成功‘)
# break
# else:
# print(‘用户名或密码错误‘)
#5 while+continue:continue的意思是结束本次循环,进入下一次循环
# n=1
# while n <= 5:
# if n == 4: #n =4
# n+=1 # n=5
# continue
# print(n)
# n+=1
# 6、练习题:循环嵌套
n=0
tag=True
while tag:
if n == 3:
print(‘失败尝试的次数过多‘)
break
name=input(‘please input your name: ‘)
pwd=input(‘please input your password: ‘)
if name == ‘egon‘ and pwd == ‘123‘:
print(‘登录成功‘)
while tag:
cmd=input(‘请输入你的命令:‘) #cmd=‘‘
# if len(cmd) == 0:continue
if not cmd:continue
if cmd == ‘q‘:
tag=False
break
print(‘%s is running‘ %cmd)
# break
else:
print(‘用户名或密码错误‘)
n+=1
#while+tag
tag=True
while tag:
print(‘第一层‘)
while tag:
print(‘第二层‘)
while tag:
cmd=input(‘第三层>>: ‘)
if cmd == ‘q‘:
tag=False
break
# break
# break
------------------------------------------------------
布尔类型
#所有的数据类型都自带布尔值
#以下数据类型自带的布尔值为假:
#0,None,空:空字符串,空列表,空字典
#
# x=‘‘
# if x:
# print(‘===>‘)
------------------------------------------------------
可变和不可变类型
# 可变:值改变,但是id不变
# 不可变:值改变,id也变。证明根本没改变原来值,而是产生新的值
# int
# x=10
# print(id(x))
# x=11
# print(id(x))
# l=[‘a‘,‘b‘,‘c‘]
# print(id(l))
# l[0]=‘A‘
# print(l)
# print(id(l))
------------------------------------------------------
数字类型
#一:int基本使用
# 1 int用途:年龄,等级,编号
# 2 定义方式
# age=18 #age=int(18)
# print(age,type(age),id(age))
# x=10 # x=int(10)
# 3 常用操作+内置的方法
# 比较大小
# 数学运算
# age=input(‘>>: ‘)
# age=int(age)
# if age > 10:
# print(‘too big‘)
# int(‘1023434234234‘) # 只有在字符中包含的字符全为阿拉伯数字的情况下,才能被int转成整型,否则 报错
# age=input(‘>>: ‘)
# age=int(age)
# if age > 10:
# print(‘too big‘)
# int(‘1023434234234‘) # 只有在字符中包含的字符全为阿拉伯数字的情况下,才能被int转成整型,否则 报错
#二:float基本使用
# 1 int用途:身高,体重,工资
# 2 定义方式
# salary=3.1 #salary=float(3.1)
# print(type(salary))
# 3 常用操作+内置的方法
# 比较大小
# 数学运算
# n=float(‘3.1‘)
# print(n,type(n))
#三:int与float类型总结
# 1 存一个值
# 2 不可变
# x=10.1
# print(id(x))
# x=11.1
# print(id(x))
# 瞅一眼
# >>> x=1-2j
# >>>
# >>> x.real
# 1.0
# >>> x.imag
# -2.0
# >>> type(x)
# <class ‘complex‘>
#python2有Long类型,python3废弃了
------------------------------------------------------
字符串类型
#一:str基本使用
# 1 用途:描述型的数据,姓名,性别,地址等
# 2 定义方式:在单引号\双引号\三引号内,包含一串字符
# name=‘egon‘ #name=str(‘egon‘)
# print(name,type(name),id(name))
#3 优先掌握的操作:
#1、按索引取值(正向取+反向取) :只能取
# msg=‘he lo‘
# print(msg[0])
# print(msg[2])
# msg[2]=‘A‘
#2、切片(顾头不顾尾,步长)
# msg=‘hello world‘
# print(msg[0:4]) #hell
# print(msg[0:4:2]) #hell
#3、长度len
# msg=‘hello‘
# print(len(msg))
#4、成员运算in和not in
# msg=‘alex say my name is alex‘
# if ‘alex‘ in msg:
# print(‘存在‘)
# print(‘alex‘ not in msg) # 推荐使用
# print(not ‘alex‘ in msg)
#5、只能移除字符串左右两边的字符strip
# name=‘x egon ‘
# name=name.strip() #默认去掉的是左右两边的空格
# print(name)
# msg=‘*****a**alex is sb*******‘
# print(msg.strip(‘*‘))
# msg=‘*****/ **alex is sb*****///// **‘
# print(msg.strip(‘* /‘))
# while True:
# # cmd=input(‘cmd>>: ‘) #cmd=‘ ‘
# # cmd=cmd.strip() #cmd=‘‘
# cmd=input(‘cmd>>: ‘).strip()
# if len(cmd) == 0:continue
# if cmd == ‘q‘:break
# print(‘%s is running‘ %cmd)
#6、split
# info=‘root:x:0:0::/root:/bin/bash‘
# res=info.split(‘:‘)
# print(res[0])
# inp=‘get a.txt‘
# cmd=inp[0:3]
# filepath=inp[4:]
# print(cmd)
# print(filepath)
# res=inp.split(‘ ‘)
# print(res)
#7、循环取值
# msg=‘egon‘
# n=0
# while n < len(msg): #0 1 2 3
# print(msg[n])
# n+=1
# for i in ‘egon‘: #i=‘g‘
# print(i)
# 需要掌握的操作
#1、strip,lstrip,rstrip
# print(‘******egon******‘.lstrip(‘*‘))
# print(‘******egon******‘.rstrip(‘*‘))
#2、lower,upper
# msg=‘Abc‘
# print(msg.lower())
# print(msg.upper())
#3、startswith,endswith
# msg=‘alex is sb‘
# print(msg.startswith(‘alex‘))
# print(msg.endswith(‘b‘))
#4、format的三种玩法
# print(‘my name is %s my age is %s‘ %(‘egon‘,18))
# print(‘my name is {name} my age is {age}‘.format(age=18,name=‘egon‘))
# 瞅一眼format的其他用法
# print(‘my name is {} my age is {}‘.format(‘egon‘,18))
# print(‘my name is {1} my age is {0} {0} {0} {0}‘.format(‘egon‘,18))
#5、split,rsplit
# info=‘root:x:0:0::/root:/bin/bash‘
# print(info.split(‘:‘,1))
# print(info.split(‘:‘,1))
# print(info.rsplit(‘:‘,1))
#6、join
# info=‘root:x:0:0::/root:/bin/bash‘
# str_to_list=info.split(‘:‘)
# print(str_to_list)
# l=[‘root‘, ‘x‘, ‘0‘, ‘0‘, ‘‘, ‘/root‘, ‘/bin/bash‘]
# list_to_str=‘:‘.join(l) #‘root‘+‘‘+‘x‘+‘‘....
# print(list_to_str,type(list_to_str))
# 注意:join只能连接所包含的元素全都为字符串类型的列表
# l=[‘a‘,2,3]
# ‘:‘.join(l) # ‘a‘+‘:‘+2+‘:‘+3
#7、replace
# msg=‘wxx say my name is wxx‘
# print(msg.replace(‘wxx‘,‘SB‘,1))
# print(msg)
#8、isdigit
# print(‘asdfa123123‘.isdigit())
# AGE=30
# while True:
# age=input(‘>>: ‘).strip()
# if not age.isdigit():continue
# age=int(age)
# if age > 30:
# print(‘too big‘)
# elif age < 30:
# print(‘to small‘)
# else:
# print(‘you got it‘)
# break
# print(r‘a\tb‘) # r开头的字符串内都是原生字符串,右斜杠没有特殊意义
# print(‘a\tb‘)
# 其他操作(了解即可)
#1、find,rfind,index,rindex,count
# msg=‘hello alex hahaha alex‘
# print(msg.find(‘alex‘,0,3)) # 找的是‘alex‘在大字符串msg中的起始索引,没有找到则返回-1
# print(msg.index(‘alex‘)) # 找的是‘alex‘在大字符串msg中的起始索引,没有找到则报错
# print(msg.count(‘alex‘))
#2、center,ljust,rjust,zfill
# print(‘info‘.center(50,‘=‘))
# print(‘info‘.ljust(50,‘=‘))
# print(‘info‘.rjust(50,‘=‘))
# print(‘info‘.zfill(50))
#3、expandtabs
# print(‘a\tb‘.expandtabs(1))
#4、captalize,swapcase,title
# print(‘abc‘.capitalize())
# print(‘Ab‘.swapcase())
# print(‘my name is egon‘.title())
#5、is数字系列
num1=b‘4‘ #bytes
num2=‘4‘ #unicode,python3中无需加u就是unicode
num3=‘肆‘ #中文数字
num4=‘Ⅳ‘ #罗马数字
#isdigit():bytes,unicode
# print(num1.isdigit())
# print(num2.isdigit())
# print(num3.isdigit())
# print(num4.isdigit())
#isnumberic:unicode,中文,罗马
# print(num2.isnumeric())
# print(num3.isnumeric())
# print(num4.isnumeric())
#isdecimal:unicode
# print(num2.isdecimal())
# print(num3.isdecimal())
# print(num4.isdecimal())
#6、is其他
# print(‘ ‘.isspace())
# print(‘abdadsf123‘.isalpha()) # 字符中是否包含的全都是字母
# print(‘123123sadfasfd‘.isalnum()) # 字符中是否包含的字母或数字
#二:str该类型总结
# 1 存一个值
# 2 有序
#
# 3不可变
x=‘abc‘
# x[0]=‘A‘
print(id(x))
x=‘bcd‘
print(id(x))
------------------------------------------------------
列表类型
#一:list基本使用
# 1 用途:存放多个值
# 2 定义方式:[]内用逗号分隔开多个元素,每个元素可以是任意数据类型
# l=[1,‘a‘,[1,2]] #l=list([1,‘a‘,[1,2]])
# 3 常用操作+内置的方法
#优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可以取也可以改
names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘yxx‘]
# print(names[4])
# print(names[-1])
# print(names[-2])
# print(id(names))
# names[0]=‘EGON‘
# print(id(names))
# print(names)
# names[5]=3 #超出索引限制就会报错
#2、切片(顾头不顾尾,步长)
names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘yxx‘]
# print(names[0:3:2])
# print(names[:])
#了解:反向步长
# print(names[3:-1:-1])
# print(names[-1::-1])
#3、长度
# names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘yxx‘]
# print(len(names))
#4、成员运算in和not in
# names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘yxx‘,1,2,3,4]
# print(‘alex‘ in names)
# print(4 in names)
#5、追加与插入
# names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘yxx‘]
# names.append(‘oldboy1‘)
# names.append(‘oldboy2‘)
# names.append(‘oldboy3‘)
# print(names)
# names.insert(2,‘oldboy‘)
# print(names)
#6、删除列表中某一个元素
names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘yxx‘]
# del names[2]
# print(names)
# res=names.remove(‘wxx‘) # 指定要删除的元素,remove方法没有返回值
# print(res)
# print(names)
#从列表中取走一个元素
# if 100 < len(names):
# res=names.pop(100) # 按照索引删除的元素(会返回刚刚删掉的元素),超过索引限制则报错
# print(names)
# print(res)
#7、循环
# names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘yxx‘,1,2,3,4]
# for x in names:
# print(x)
# 需要掌握的操作
names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘xxx‘,‘yxx‘,1,2,3,4]
# names.reverse()
# names.reverse()
# print(names)
# names.count()
# print(names.count(‘xxx‘))
# names.clear()
# names.clear()
# print(names)
# names.copy()
# l=names.copy()
# print(l)
# names.index()
# names=[‘egon‘,‘alex‘,‘wxx‘,‘xxx‘,‘xxx‘,‘yxx‘,1,2,3,4]
# print(names.index(‘alexasdf‘))
# names.sort(): 列表中的元素必须是同一类型才能比较排序
# names=[‘b‘,‘a‘,‘+‘]
# names.sort()
# print(names)
# 了解:字符\|列表之间比较大小
# x=‘hello‘
# y=‘z‘
# print(y > x)
#排序:‘A-Za-z‘
# l1=[1,2,‘a‘,‘b‘]
# l2=[1,2,‘b‘]
#
# print(l2 > l1)
#二:该类型总结
# 1 存多个值
# 2 有序
# 3 可变
#练习题:
#1 队列:先进先出
l=[]
# 入队:first->second->third
# l.append(‘first‘)
# l.append(‘second‘)
# l.append(‘third‘)
# print(l)
# 出队:
# print(l.pop(0))
# print(l.pop(0))
# print(l.pop(0))
#2 堆栈:先进后出
# 入栈:first->second->third
l.append(‘first‘)
l.append(‘second‘)
l.append(‘third‘)
# 出栈:third->second->first
print(l.pop(-1))
print(l.pop())
print(l.pop())
------------------------------------------------------
元组类型
#一:tuple基本使用
# 1 用途: 不可变的列表
# 2 定义方式
# t=(1,2,3) #t=tuple((1,2,3))
# print(type(t))
# 3 常用操作+内置的方法
#优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取
# t=(‘a‘,‘b‘,‘c‘)
# print(t[-1])
# t[-1]=33333
#2、切片(顾头不顾尾,步长)
# t=(‘a‘,‘b‘,‘c‘,‘d‘,‘e‘)
# print(t[0:5:2])
#3、长度
#4、成员运算in和not in
#5、循环
# 需要掌握的方法
# t=(‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘c‘)
# print(t.index(‘c‘))
# print(t.count(‘c‘))
#
#二:该类型总结
# 1 存多个值
# 2 有序
#
# 3 不可变
------------------------------------------------------
字典类型
#一:dict基本使用
# 1 用途:存多个值,key:value,key对value有描述的作用
#
# 2 定义方式:{}内用逗号分开多个元素,每一个元素都是key:value的形式
#其中key必须是不可变类型,key通常都应该是字符串类型
#其中value可以是任意数据类型
# info={‘name‘:‘egon‘,(1,2):18} #info=dict({‘name‘:‘egon‘,‘age‘:18})
# print(info[‘name‘])
# print(info[(1,2)])
# 3 常用操作+内置的方法
#优先掌握的操作:
#1、按key存取值:可存可取
# d={‘x‘:1}
# print(id(d))
# d[‘x‘]=2
# print(id(d))
# print(d)
# d[‘y‘]=3
# print(d)
#2、长度len
# info={‘x‘:1,‘y‘:2,‘z‘:3}
# print(len(info))
#3、成员运算in和not in :判断的是字典的key
# info={‘x‘:1,‘y‘:2,‘z‘:3}
# print(‘x‘ in info)
#4、删除
info={‘x‘:1,‘y‘:2,‘z‘:3}
# del info[‘x‘]
# print(info)
# print(info.popitem())
# print(info.pop(‘xxxxx‘,None))
# print(info)
#5、键keys(),值values(),键值对items()
msg_dic={
‘apple‘:10,
‘tesla‘:100000,
‘mac‘:3000,
‘lenovo‘:30000,
‘chicken‘:10,
}
# print(msg_dic.keys())
#6、循环
# msg_dic={
# ‘apple‘:10,
# ‘tesla‘:100000,
# ‘mac‘:3000,
# ‘lenovo‘:30000,
# ‘chicken‘:10,
# }
# for k in msg_dic:
# print(k,msg_dic[k])
# for k in msg_dic.keys():
# print(k)
# for v in msg_dic.values():
# print(v)
#k,v=(‘apple‘, 10)
# for k,v in msg_dic.items(): #[(‘apple‘, 10), (‘tesla‘, 100000), (‘mac‘, 3000), (‘lenovo‘, 30000), (‘chicken‘, 10)]
# print(k,v)
# 掌握的操作
msg_dic={
‘apple‘:10,
‘tesla‘:100000,
‘mac‘:3000,
‘lenovo‘:30000,
‘chicken‘:10,
}
# if ‘applexxxxx‘ in msg_dic:
# print(msg_dic[‘applexxxxx‘])
# print(msg_dic.get(‘apple111‘,123123123123))
# msg_dic.update
# d1={‘x‘:1,‘y‘:2}
# d1.update({‘x‘:2,‘z‘:3})
# print(d1)
# msg_dic.setdefault
#1、key存在,则不改变key对应的值,放回原值
# d={‘x‘:1,‘y‘:2}
# res=d.setdefault(‘x‘,1000)
# # print(d)
# print(res)
#2、key不存在,则增加一个key:value,返回新增的value
# d={‘x‘:1,‘y‘:2}
# res=d.setdefault(‘z‘,1000)
# print(d)
# print(res)
#总结:setdefault有则不变,无则增加
s=‘hello alex alex say hello sb sb‘
words=s.split()
d={}
for word in words:
# if word not in d:
# d[word]=1 #d={‘hello‘:1,‘alex‘:1}
# else:
# d[word]+=1
d.setdefault(word,words.count(word))
print(d)
# 了解
# d={}.fromkeys([‘name‘,‘age‘,‘sex‘],None)
# print(d)
#二:dict该类型总结
# 1 存多个值
#
# 2 无序
#
# 3 可变
------------------------------------------------------
作业:
menu = {
‘北京‘:{
‘海淀‘:{
‘五道口‘:{
‘soho‘:{},
‘网易‘:{},
‘google‘:{}
},
‘中关村‘:{
‘爱奇艺‘:{},
‘汽车之家‘:{},
‘youku‘:{},
},
‘上地‘:{
‘百度‘:{},
},
},
‘昌平‘:{
‘沙河‘:{
‘老男孩‘:{},
‘北航‘:{},
},
‘天通苑‘:{},
‘回龙观‘:{},
},
‘朝阳‘:{},
‘东城‘:{},
},
‘上海‘:{
‘闵行‘:{
"人民广场":{
‘炸鸡店‘:{}
}
},
‘闸北‘:{
‘火车战‘:{
‘携程‘:{}
}
},
‘浦东‘:{},
},
‘山东‘:{},
}
tag=True
while tag:
menu1=menu
for key in menu1: # 打印第一层
print(key)
choice1=input(‘第一层>>: ‘).strip() # 选择第一层
if choice1 == ‘b‘: # 输入b,则返回上一级
break
if choice1 == ‘q‘: # 输入q,则退出整体
tag=False
continue
if choice1 not in menu1: # 输入内容不在menu1内,则继续输入
continue
while tag:
menu_2=menu1[choice1] # 拿到choice1对应的一层字典
for key in menu_2:
print(key)
choice2 = input(‘第二层>>: ‘).strip()
if choice2 == ‘b‘:
break
if choice2 == ‘q‘:
tag = False
continue
if choice2 not in menu_2:
continue
while tag:
menu_3=menu_2[choice2]
for key in menu_3:
print(key)
choice3 = input(‘第三层>>: ‘).strip()
if choice3 == ‘b‘:
break
if choice3 == ‘q‘:
tag = False
continue
if choice3 not in menu_3:
continue
while tag:
menu_4=menu_3[choice3]
for key in menu_4:
print(key)
choice4 = input(‘第四层>>: ‘).strip()
if choice4 == ‘b‘:
break
if choice4 == ‘q‘:
tag = False
continue
if choice4 not in menu_4:
continue
原文地址:https://www.cnblogs.com/polly-meng/p/8783100.html