标签:while循环
第 7 章讲了用户输入 input( ) 和 while 循环,内容如下
input( ) 工作原理
超过一行的 input( )
int( ) 来获取数字的输入,进行比较
求模运算
简单的 while 循环。我自己的理解就是设定一个条件,while 满足这个条件开始循环,不满足退出
break 直接退出
continue 跳出当前层的循环
避免无限循环
while 在列表中的应用
while 删除列表中指定的字符串 remove()
用户输入的字符来填充字典
input( ) 工作原理
首先定义 input( ) 函数括号中向用户显示提示说明,让用户输入内容
在将用户输入的内容保存到变量 message 中,最后打印
-------------------------------------------------------------------------------------------
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
-------------------------------------------------------------------------------------------
Tell me something, and I will repeat it back to you: haha
haha
编写清晰的程序
---------------------------------------------------------
name = input("Please enter your name: ")
print("Hello, " + name + "!")
---------------------------------------------------------
Please enter your name: python
Hello, python!
超过一行的 input
如果想打印多行提示信息,可以使用 +=
-------------------------------------------------------------------------------------------
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
-------------------------------------------------------------------------------------------
If you tell us who you are, we can personalize the message you see.
What is your first name? python
Hello, python!
使用 int( ) 来获取数值输入
如果不指定 age=int(age),python将会报错
-------------------------------------------
age = input("How old are you? ")
print(age)
age = int(age)
if age >= 18:
print(age)
-------------------------------------------
How old are you? 29
29
29
int( ) 进行数值比较,进行测试
--------------------------------------------------------------------------------
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou‘re tall enough to ride!")
else:
print("\nYou‘ll be able to ride when you‘re a little older.")
--------------------------------------------------------------------------------
How tall are you, in inches? 89
You‘re tall enough to ride!
求膜运算符
两个数相除,返回余数
---------------------
print(4 % 3)
print(5 % 3)
print(6 % 3)
print(7 % 3)
----------------------
1
2
0
1
可以利用求模来计算一个数是奇数还是偶数
-------------------------------------------------------------------------------------------
number = input("Enter a number, and I‘ll tell you if it‘s even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.")
-------------------------------------------------------------------------------------------
Enter a number, and I‘ll tell you if it‘s even or odd: 78
The number 78 is even.
while 循环
如果 while 小于等于 5,就一直运行
打印一次后,就将 current_number 的数值 +1
--------------------------------------
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
--------------------------------------
1
2
3
4
5
让用户选择何时退出
如果用户不输入 quit,就一直循环下去
-------------------------------------------------------------------------------------
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter ‘quit‘ to end the program. "
message = ""
while message != ‘quit‘:
message = input(prompt)
print(message)
-------------------------------------------------------------------------------------
Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program. zhao
zhao
Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program. shanshan
shanshan
Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program. quit
quit
进行更改
上面的程序在用户输入 quit 时,也会将 quit 作为消息在打印一遍
代码中并没有定义如果用户输入 quit 会怎么样,所以当用户输入 quit
直接结束循环,退出
-------------------------------------------------------------------------------------
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter ‘quit‘ to end the program. "
message = ""
while message != ‘quit‘:
message = input(prompt)
if message != ‘quit‘:
print(message)
-------------------------------------------------------------------------------------
Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program. zhao
zhao
Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program. quit
继续改进上面的代码
就像刚才说的,并没有指定如果用户输入 quit 会怎么样
其实在 while 循环中嵌套一个 if-else 语句就可以了
但是开始循环时,先定义一个 active=True
如果是 True 就循环,是 False 就停止循环
------------------------------------------------------------------------------------
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter ‘quit‘ to end the program. "
active = True
while active:
message = input(prompt)
if message == ‘quit‘:
active = False
else:
print(message)
------------------------------------------------------------------------------------
Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program. zhao
zhao
Tell me something, and I will repeat it back to you:
Enter ‘quit‘ to end the program. quit
break 直接退出循环
还是以上面的代码为例,当用户输入 break 时,直接 break,结束当前的 while 循环
-----------------------------------------------------------------------------------
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter ‘quit‘ when you are finished.)"
while True:
city = input(prompt)
if city == ‘quit‘:
break
else:
print("I‘d love to go to " + city.title() + "!")
-----------------------------------------------------------------------------------
Please enter the name of a city you have visited:
(Enter ‘quit‘ when you are finished.)zhao
I‘d love to go to Zhao!
Please enter the name of a city you have visited:
(Enter ‘quit‘ when you are finished.)shushu
I‘d love to go to Shushu!
Please enter the name of a city you have visited:
(Enter ‘quit‘ when you are finished.)quit
continue 跳出当前的循环
每循环一次就 +1,当 current_number 可以被 2 整除的时候
就执行 continue,跳出这一层循环,继续 while 的下一次循环
------------------------------------------
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
------------------------------------------
1
3
5
7
9
避免无限循环
死循环代码如下,x 开始等于 1,在第一次循环结束后并没有变,
一直等于 1,永远满足 x <= 5 的条件,所以会被一直打印
------------------
x = 1
while x <= 5:
print(x)
------------------
正常代码
需要指定一个条件,每循环一次 x 的值都 +1
------------------
x = 1
while x <= 5:
print(x)
x += 1
------------------
while 在列表中的应用
-----------------------------------------------------------------------
unconfirmed_users = [‘alice‘, ‘brian‘, ‘candace‘]
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
-----------------------------------------------------------------------
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
删除包含特定值的所有列表元素
while 中一直执行 remove( ) 删除列表中的 cat 字符
----------------------------------------------------------------------
pets = [‘dog‘, ‘cat‘, ‘dog‘, ‘goldfish‘, ‘cat‘, ‘rabbit‘, ‘cat‘]
print(pets)
while ‘cat‘ in pets:
pets.remove(‘cat‘)
print(pets)
----------------------------------------------------------------------
[‘dog‘, ‘cat‘, ‘dog‘, ‘goldfish‘, ‘cat‘, ‘rabbit‘, ‘cat‘]
[‘dog‘, ‘dog‘, ‘goldfish‘, ‘rabbit‘]
用户输入来填充字典
定义一个空的字典 responses
定义 polling_active = True 开始循环,等于 False 退出循环
让用户分别输入 name,response
responses[name] = response 将用户输入的添加到 responses 字典中
for 循环 items( ) 遍历 responses 字典
-------------------------------------------------------------------------------------------
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respind? (yes/ no) ")
if repeat == ‘no‘:
polling_active = False
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
-------------------------------------------------------------------------------------------
What is your name? shanshan
Which mountain would you like to climb someday? taiqiu
Would you like to let another person respind? (yes/ no) no
--- Poll Results ---
shanshan would like to climb taiqiu .
本文出自 “LULU” 博客,请务必保留此出处http://aby028.blog.51cto.com/5371905/1965223
标签:while循环
原文地址:http://aby028.blog.51cto.com/5371905/1965223