while
用户输入和while循环
Input():等待用户输入一些文本,获取用户输入后,将其存储在一个变量中
message=input("Tell me something,and I will repeat it back to you:")
print("\n"+message)
注:此方法不管输入的是字母还是数字,统一会转化为str类型
使用int()来获取数值输入:
age=int(input("How old are you?"))
if age>=18:
print("Hello!young people!")
else:
print("Hello!children!")
求模运算:a=3%2 将两个数相除并返回余数
注:在Python2中获取输入是raw_input
While:for循环是对集合中每一个元素都一个代码块,while循环是不断运行着,直到指定条件不满足
使用while:
b=1
while b<=3:
print(b)
b=b+1
让用户选择何时退出:
c=''
while c!='quit':
c=input('please input:')
if(c!='quit'):
print(c)
使用标志:当多个事件都可会使程序停止运行,设置一个标志量比设置多个判断条件要好的多
c=True
while c:
c=input('please input:')
if(c=='quit' or c=='esc'):
c=False
else:
print(c)
使用break退出循环:
while True:
c=input('please input:')
if(c=='quit' or c=='esc'):
break
print(c)
注:如果程序陷入无限循环可以按ctrl+z
在循环中使用continue:
Continue:从此处直接返回到开头,然后根据while的循环条件是否满足来决定是否要继续运行循环
d=0
while d<5:
d+=1
if d%2==0:
print(d)
continue
print('I can print?')
使用while循环来处理列表和字典:
原因:for循环是一种遍历列表的有效方式,但是for循环中不应该修改列表,否则将导致python难以跟踪其中的元素,所以如果想在遍历列表的同时对其进行修改,可以使用while
- 1.在列表之间移动元素
a=['b','c','d']
aa=[]
while a:
x=a.pop()
aa.append(x)
for y in aa:
print(y)
- 删除包含特定值的所有列表元素:
在之前我们用remove()来删除列表中的特定值,他只能删除列表中出现的第一个特定值,但是如果后面还有相同的值,是无法删除的,所以:
pets=['dog','cat','cat','goldfish']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
- 使用用户输入来填充字典: