用户输入和while循环
函数input()的工作原理
message=input("input and repeat: ")
print(message)
//input
james
//output
james
函数input()接受一个参数,即键入值;input()函数会先输出信息,然后等待输入,并在回车键键入后继续运行。
使用int()来获取数值输入
messgae=input("How old are u:")
print(message)
message=int(message)
print(message)
//input
19
//output
19
19
这个例子可能不是很体现的出来,但是使用input()时,python会将输入解读为字符串。
使用int()是希望能够进行强制类型转换,将字符换类型转换成int类型。
求模运算符
%运算符:使用与C++无异。
while循环
number=1
while number<=5:
print(number)
number+=1
//OUTPUT
1
2
3
4
5
使用break退出循环
与if联用,与C++无异;
使用continue
与if联用,与C++无异。
使用while循环来处理列表与字典
unconfirmed=['alice','brian','candace']
confirmed=[]
while unconfirmed:
user=unconfirm.pop()
confirmed.append(user)
print(confirmed)
//OUTPUT
['candace', 'brian', 'alice']
删除列表元素
//删除列表中特殊值的元素
pets=['dog','cat','fish']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
//output
['dog', 'cat', 'fish']
['dog', 'fish']
使用输入来填充字典
设置一个标志Flag,来标志是否继续进行字典的填充,若否,则令Flag=false