17.input 工作原理
input()
函数input接受一个参数,即向用户显示的提示或说明,然后将其储存在一个变量当中
message=input('tell me something')
print(message)
输入的内容在对话框中进行输入,input用于在输入时提示用户,但是默认使用input时输入的是字符串类型
int( )
c语言中使用(int),(double)后接一些数值或者变量来进行强制转换,而在python中对输入的带有’ '的字符中存在的数字,使用int()来进行转化
hei=input('how tall are you?')
height=int(hei)
print(height>=18)
结果
how tall are you?56
True
18.while循环
while循环中一定要有使循环条件不满足的时候进行退出的条件
prompt='tell me something'
prompt+='enter quit to end this program'
message=''
while message !='quit':
message=input(prompt)
if message!='quit':
print(message)
结果
tell me somethingenter quit to end this programhello world !
hello world !
tell me somethingenter quit to end this programend world!
end world!
tell me somethingenter quit to end this programquit
使用标志
利用第三变量来帮助while控制循环的结束,即当达到某一条件时,改变此标志来结束程序
prompt='tell me something'
prompt+='enter quit to end this program\n'
active=True
while active:
message=input(prompt)
if message!='quit':
print(message)
else:
active=False
结果
tell me somethingenter quit to end this program
hello world !
hello world !
tell me somethingenter quit to end this program
end world
end world
tell me somethingenter quit to end this program
quit
上面程序中active即是改变while循环的标志
break与continue
prompt='tell me something'
prompt+='enter quit to end this program\n'
active=True
while active:
message=input(prompt)
if message!='quit':
print(message)
else:
break
结果
tell me somethingenter quit to end this program
hello
hello
tell me somethingenter quit to end this program
quit
current=0;
while current<10:
current += 1
if current % 2==0:
continue
print(current)
结果
1
3
5
7
9
在使用continue和break时,注意后面print语句的缩进距离,当与if平齐或考后,若超过if将不再能够输出1-9,而是只输出一个10或者运行错误,达不到输出偶数的效果
使用while操作字典与列表
unname=['alice','brian','candace']
value=[]
new=[]
while unname:#即当unname不为空时进入此循环
value=unname.pop()
print(value)
new.append(value)
print(new)
print(value)
结果
candace
brian
alice
['candace', 'brian', 'alice']
alice
注意,在最后的输出中看到,value中每次只保存了一个变量alice,需要保存整个列表要用append来存在new这个新的列表中,每次将value的变值存进去new中。
remove.()
此命令,能够永久地对列表操作删除,类似此前的pop和del
pets=['dog','cat','dog','goldfish','cat','rabbit']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
结果
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit']
['dog', 'dog', 'goldfish', 'rabbit']