while循环
一般格式
while+判断条件:
(四个空格)要执行的语句
判断条件返回的结果应该是一个布尔型的 要么为True要么为False
以while True:开头的循环就会被不断地运行,是无限循环
#如果程序陷入无限循环可以按ctrl+c结束
x = 1
while x < 5:
print(x)
运行后无限循环打印出无数多个1 此时按ctrl+c即可结束这个无限循环
#现在希望第一次完整打印一个字符串 然后第二次打印时少一个字母 第三次时又少一个 如此循环直到没有字母
x = 'youpinketang'
while x:
#字符串只要有值就为True 空字符串时才为False才会停止
print(x, end=' ')
#打印完之后,把字符串序列里的第二位到最后一位取出来重新赋值给x
x = x[1:]
youpinketang oupinketang upinketang pinketang inketang nketang ketang etang tang ang ng g
字符串:只要有值就为True 空字符串为False
列表:列表里有元素就为True 空列表为False
int型:大于0的为True 0为False
a, b = 0, 10
while a < b:
print(a)
a += 1
#+=表示符号两边的值相加然后赋给符号左边的变量 a+=1表示a=a+1
0
1
2
3
4
5
6
7
8
9
Process finished with exit code 0
break
break会跳出整个while循环
word1 = 'Please enter your fav city'
word1 += '\nEnter quit when you want to quit'
while True:
city = input(word1)
if city == 'quit':
break
else:
print('I love ' + city.upper() + ' too!')
#以while True:开头的循环将会无限循环不断运行,直到遇到break语句。当用户输入某个城市时,不满足if,执行else后面的print 然后继续循环又显示word1 直到用户输入quit 满足if,执行if后面的break,导致python退出循环
Please enter your fav city
Enter quit when you want to quitNew York
I love NEW YORK too!
Please enter your fav city
Enter quit when you want to quitSan Francisco
I love SAN FRANCISCO too!
Please enter your fav city
Enter quit when you want to quitTokyo
I love TOKYO too!
Please enter your fav city
Enter quit when you want to quitLos Angles
I love LOS ANGLES too!
Please enter your fav city
Enter quit when you want to quitquit
Process finished with exit code 0
while True:
name = input('请输入您的姓名: ')
if name == 'quit':
break
age = input('请输入您的年龄: ')
print('hello {}-year-old {} ,welcome to python world! '.format(age, name))
print('循环结束')
#首先会显示输入姓名,然后如果输入的姓名不是quit,则继续显示输入年龄,然后打印,然后继续执行循环显示输入姓名.....直到输入quit后,满足if——>执行break——>跳出while循环外面,执行print(‘循环结束’)
请输入您的姓名: Ari
请输入您的年龄: 18
hello 18-year-old Ari ,welcome to python world!
请输入您的姓名: Tom
请输入您的年龄: 20
hello 20-year-old Tom ,welcome to python world!
请输入您的姓名: quit
循环结束
Process finished with exit code 0
while True:
name = input('请输入您的姓名: ')
if name == 'quit':
break
age = input('请输入您的年龄: ')
print('hello {}-year-old {} ,welcome to python world! '.format(age, name))
else:
print('循环结束')
请输入您的姓名: Ari
请输入您的年龄: 18
hello 18-year-old Ari ,welcome to python world!
请输入您的姓名: quit
Process finished with exit code 0
#发现这一次输入quit——>满足if——>break跳出while循环后 并没有执行print(‘循环结束’) 这是因为while xxx: else:xxx 均属于while循环代码块里,而break会导致跳出整个while循环体 所以就不会执行print(‘循环结束’)
continue
continue会返回到循环的开头,并根据条件测试的结果决定是否继续执行循环
#假定我现在只想打印10以内的偶数
x=10
# while x:表示只要x为True即x不等于0 就怎么怎么样
while x:
x -= 1
if x % 2 != 0:
continue
#上述代码表示:只要x不等于0 就减去1 然后如果x除以2余数不等于0 则回到循环的开头while x:而不执行下面print的代码 如果x除以2余数为0 则不通过if测试 不执行跟在if后面的continue而执行下面的print()
print(x, end=' ')
8 6 4 2 0
Process finished
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue
else:
print('odd number: ' + str(number))
#首先将number设置为0,由于它小于10通过条件测试,因此进入循环,首先加1 因此number=1 然后判断它除以2的余数是否等于0,如果为0则执行if后面的语句continue 执行continue语句后python会忽略余下的代码并返回到循环的开头继续判断是否继续循环;如果不为0则不满足if,执行else后面的print()语句打印出number
odd number: 1
odd number: 3
odd number: 5
odd number: 7
odd number: 9
Process finished with exit code 0
practice
让用户选择何时退出
#让用户选择何时退出——可使用while循环让程序在用户愿意时不断运行。在代码中定义一个退出值,只要用户输入的不是这个值,程序就会接着运行。
word1 = 'Tell me something and i will repeat it to you'
word1 += '\nenter quit to end the program'
#首先我们声明一个字符串,定义一条提示消息,告诉用户输入某些信息或者输入quit终止程序
message = ''
#将变量message的初始值设置为一个空字符串‘’,让python首次执行while代码行时有可供检查的东西。python首次执行while语句时,需要将message的值和quit进行对比,只要message的值不是quit,这个循环就会不断运行。首次遇到这个循环时,message是一个空字符串,因此不等于quit,进入循环
while message != 'quit':
message = input(word1)
if message != 'quit':
print(message)
Tell me something and i will repeat it to you
enter quit to end the program i love you
i love you
Tell me something and i will repeat it to you
enter quit to end the programquit quit
Process finished with exit code 0
#只要用户输入quit,通不过while的条件测试,就停止循环,程序结束
在列表之间移动元素
假设有一个列表,其中包含着未验证的用户;现在想验证这些用户后将他们移动到另一个已验证用户列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
#上述while语句将一直执行直到列表变成空的
current_users = unconfirmed_users.pop()
#list.pop()方法将以每次一个的方式从列表末尾删除一个元素,然后将其储存在变量current_users中
print('verifying user: ' + current_users.title())
confirmed_users.append(current_users)
#将current_users追加到列表中
#当列表里元素被删除光了之后,不再执行while循环,跳出循环执行下面的代码
print('the following users have been confirmed: ')
for x in confirmed_users:
print(x)
verifying user: Candace
verifying user: Brian
verifying user: Alice
the following users have been confirmed:
candace
brian
alice
Process finished with exit code 0
删除包含特定值的所有列表元素
假设现有一个列表,里面包含多个重复元素 现想删除所有重复的元素
#当1在列表里时,进入循环,删除一个1,再返回循环开头检查1在不在列表里,仍在则继续删除一个。直到1不在列表里,跳出循环,打印列表
l = [1, 1, 2, 3, 4, 5, 6, 1, 1, 1, 7]
while 1 in l:
l.remove(1)
print(l)
[2, 3, 4, 5, 6, 7]
Process finished with exit code 0
使用用户输入填充字典
#首先设置一个标志命名为active 只要active为True,while循环就一直执行下去
active = True
responses = {}
while active:
name = input('what is your name?')
word = input('which city do you want to go?')
responses[name] = word
repeat = input('would you like to let another person respond?(yes/no)')
#如果输入no active就被设置为False,此时回到while循环开头发现不满足条件,while循环结束跳出循环,运行下一块代码块
if repeat == 'no':
active = False
for name, response in responses.items():
print(name + ' want to go to ' + response)
what is your name?Arianna
which city do you want to go?New York
would you like to let another person respond?(yes/no)yes
what is your name?Jack
which city do you want to go?Tokyo
would you like to let another person respond?(yes/no)no
Arianna want to go to New York
Jack want to go to Tokyo
Process finished with exit code 0