用户输入和while循环

函数input()的工作原理

message=input('Tell me something,and I will repeat it back to you:')
print(message)

编写清晰的程序

#有时,提示可能超过一行,可将提示存储在一个变量中,再将该变量传递给函数input()。
prompt='If you tell us who you are,we can personalize the message you see.'
prompt+='
What is your first name?'
#第一行将消息的前半部分存储进变量
#第二行运算符‘’+=‘在存储在变量中的字符串末尾附加一个字符串
name=input(prompt)
print('
Hello, ' + name + '!')

使用while循环

current_number=1
while current_number<=5:
	print(current_number)
	current_number+=1

使用标志

active=True                         #变量active设置成True,让程序最初处于活动状态。
while active:                       #只要变量为True,循环将继续进行
	message=input('>>:')  
	if message=='quit':
		active=False        #输入‘quit’,变量设置为False,导致while不再循环
	else:
		print(message)

使用break退出循环

active=True
while active:
	message=input('>>:')
	if message=='quit':
		break
	else:
		print(message)

再循环中使用continue

current_number=0
while current_number<10:
	current_number+=1
	if current_number%2==0:
		continue     # 变量是偶数,执行continue语句,忽略余下代码,返回循环的开头
	print(current_number)
打印出来
1
3
5
7
9

在列表之间移动元素

unconfirmed_users=['alice','brian','candace',]
confirmed_users=[]
while unconfirmed_users:
	
	current_user=unconfirmed_users.pop()
	confirmed_users.append(current_user)
for confirmed_user in confirmed_users:
	print(confirmed_user.title())

删除包含特定值的所有列表

sandwich_orders=['jjc','wcx','bbb','pastrami','pastrami','pastrami']
finished_sandwichs=[]
print('pastrami is finished')
while 'pastrami' in sandwich_orders:  #删除特定值
	sandwich_orders.remove('pastrami')
print(sandwich_orders)
for sandwich_order in sandwich_orders:
	finished_sandwichs.append(sandwich_order)
	print('I made your ' + sandwich_order + ' sandwich')
for finished_sandwich in finished_sandwichs:
	print(finished_sandwich)
原文地址:https://www.cnblogs.com/rener0424/p/10086650.html