《Python编程:从入门到实践》笔记。python
本章主要介绍如何进行用户输入,
while
循环,以及与循环配合使用的break
,continue
语句。编程
在Python中,使用input()
函数获取用户输入,这里请注意:input()
的返回值为字符串。若是输入的是数字,而且要用于后续计算,须要进行类型转换。 input()
函数能够传入字符串参数做为输入提示,以下:微信
# 代码:
number = input()
# 判断数据类型的两种方法
print(type(number))
print(isinstance(number, str))
print(int(number) ** 2) # int()函数将字符串转换成整数
# 若是提示超过一行,能够将提示放在变量中,再将变量传入input();
# 而且最好在提示后面留一个空格以区分提示和用户输入
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# 结果:
123
<class 'str'>
True
15129
Tell me something, and I will repeat it back to you: Hello, everyone!
Hello, everyone!
复制代码
判断奇偶(做为对前文常见运算的补充):取模运算%
,返回余数app
# 代码:
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2:
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: 123
The number 123 is even.
复制代码
for
循环用于针对集合中的每一个元素的一个代码块,而while
循环不断地运行,直到指定的条件不知足为止。好比,让用户选择什么时候退出:函数
# 代码:
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. Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
复制代码
在上述代码中咱们直接对输入数据进行判断,这样作在简单的程序中可行,但复杂的程序中,若是有多个状态同时决定while
循环的继续与否,要是还用上述的方法,则while
循环的条件判断将很长很复杂,这时能够定义一个变量做为标志来代替多个条件。使用标志来改写上述代码:测试
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)
复制代码
在复杂的程序中,如不少事件都会致使程序中止运行的游戏中,标志颇有用:在其中的任何一个事件致使活动标志变为False
时,主游戏循环将退出。网站
要当即退出while
或者for
循环,不在执行循环中余下的代码,也无论条件测试的结果如何,可以使用break
语句。再将上述使用标志的代码改写为break:ui
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
while True:
message = input(prompt)
if message != "quit":
break
print(message)
复制代码
若是知足某条件时要返回循环开始处,而不是跳出循环,则使用continue
语句。如下是打印1到10中的全部奇数的代码:spa
# 代码:
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue
print(count)
# 结果:
1
3
5
7
9
复制代码
break与continue的区别:break
跳过循环体内余下的全部代码,并跳出循环;continue
跳过循环体内余下的全部代码,回到循环体开始处继续执行,而不是跳出循环体。 值得提醒的是,编写循环时应避免死循环,或者叫作无限循环,好比while
循环忘记了变量自增。.net
将未验证用户经验证后变为已验证用户:
# 代码:
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
复制代码
以前的章节中使用remove()
函数来删除列表中的值,但只删除了列表中的第一个指定值,如下代码循环删除列表中指定的值:
# 代码:
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
while polling_active:
# 提示输入被调查者的名字和回答
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# 将回答存入字典
responses[name] = response
# 是否还有人要参与调查
repeat = input("World you like to let another person respond?(yes/ no) ")
if repeat == "no":
polling_active = False
# 调查结束,输出结果
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " world like to climb " + response + ".")
# 结果:
What is your name? Eric
Which mountain would you like to climb someday? Denali
World you like to let another person respond?(yes/ no) yes
What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
World you like to let another person respond?(yes/ no) no
--- Poll Results ---
Eric world like to climb Denali.
Lynn world like to climb Devil's Thumb.
复制代码
迎你们关注个人微信公众号"代码港" & 我的网站 www.vpointer.net ~