Python-7.1-用户输入和while
用户输入
一:函数input()的工作原理
- 函数input()让程序暂停运行,等待用户输入一些文本。获取文本后,Python将其存储在一个变量中,方便使用。
1、编写清晰的程序
- 每当使用函数input()时,都应指定清晰而易于明白的提示
- 准确地指出你希望用户提供什么样的信息
#提示用户输入的信息
prompt = "There are many fruits."
#运算符 += 在存储在prompt中的字符串末尾附加一个字符串
prompt += "\nPlease choose your favorite fruit : "
#调用函数input()
fruit = input(prompt)
print("You like " + fruit + ".")
There are many fruits.
Please choose your favorite fruit : apple
You like apple.
2、使用int()来获取数值输入
- 使用函数input()时,Python将用户输入的文本解读为字符串
- 字符串与整数无法比较,可调用函数int()将数字的字符串转换为数值
#int()将数字的字符串转换为数值案例
prompt = "Enter your score : "
#提示用户从键盘输入
score = input(prompt)
#将数字字符串转换为数值
score = int(score)
if score > 90 :
print("You get A !")
Enter your score : 91
You get A !
3、求模运算符
- 求模运算符不会指出一个数是另一个数的多少倍,而只指出余数多少
#判断一个数是偶数是奇数
prompt = "Enter a number : "
#提示用户从键盘输入一个数字
number = input(prompt)
#将数字字符串转换成数值
number = int(number)
#如果模运算的结果为0,则这个数是偶数
if number % 2 == 0 :
print("The number " + str(number) + " is even.")
#如果模运算的结果不为0,则这个数是奇数
else :
print("The number " + str(numben) + " is odd.")
Enter a number : 8
The number 8 is even.
while循环
一:while循环简介
- for循环用于针对集合中的每个元素的一个代码块,而while循环不断地运行,直到指定的条件不满足为止
1、使用while循环
- 使用while循环来数数
#while循环案例
number = 1
#使用while直到数为5时,停止循环
while number <= 5 :
#打印数字
print(number)
#number循环一次不断加1,直至加到5为止
number += 1
1
2
3
4
5
2、让用户选择何时退出
- 定义一个退出值’quit’,只要用户输入的不是这个值,程序就接着运行
- 定义一个变量message,首次遇到这个循环时,meeage是一个空字符串,与退出值’quit’比较,因此Python进入这个循环。执行到代码行message = input(prompt)时,Python显示提示消息,并等待用户输入。不管用户输入是什么,都将存储到变量message中并打印出来;接下来,Python重新检查while语句中的条件。只要用户输入的不是退出值’quit’,Python就会再次显示提示消息并等待用户输入。等到用户终于输入’quit’后,Python停止执行while循环,而整个程序到此结束
#定义提示信息
prompt = "\nTell me something , and I will repeat it back to you : "
prompt += "\nEnter 'quit' to end up the program."
#将变量message的初始值设置为空字符串" "
#让Python首次执行while代码行时有可供检查的东西
#Python首次执行while语句时,需将message的值和'quit'比较
message = " "
#首次message中的空字符串与'quit'比较,不等于,循环
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 up the program.APPLE
APPLE
Tell me something , and I will repeat it back to you :
Enter ‘quit’ to end up the program.BANANA
BANANA
Tell me something , and I will repeat it back to you :
Enter ‘quit’ to end up the program.QUIT
QUIT
Tell me something , and I will repeat it back to you :
Enter ‘quit’ to end up the program.quit
3、使用标志
- 在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为“标志”
- 标志为True时继续运行,标志为False时停止运行
4、使用break退出循环
- 要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句
- break语句用于控制程序流程,可使用它来控制哪些代码将执行,哪些代码不执行
- 在任何Python循环中都可使用break语句
- 可使用break语句来退出遍历列表或字典的for循环
#使用标志案例
#使用break语句案例
prompt = "\nTell me something , and I will repeat it back to you : "
prompt += "\nEnter 'quit' to end up the program."
#将变量active设置为True,让程序最初处于活跃状态
active = 'True'
#当程序处于活跃True时,程序将执行
while active :
#提示用户从键盘输入信息
message = input(prompt)
#当输入的为'quit'时
if message == 'quit' :
#变量active将设置为False
active = 'False'
print("Game over")
#使用while语句,退出循环
break
else :
print("Message : \nI like " + str(message) + ".")
Tell me something , and I will repeat it back to you :
Enter ‘quit’ to end up the program.apple
Message :
I like apple.
Tell me something , and I will repeat it back to you :
Enter ‘quit’ to end up the program.quit
Game over
5、在循环中使用continue
- 要返回到循环开头,并根据条件测试结果是否继续执行循环,可使用continue语句
- 不像break语句那样不再执行余下的代码并退出整个循环
#10以内的奇数
prompt = "Enter a number "
#初始变量number为0
number = 0
#使用while循环直至number小于10
while number < 10 :
#number循环一次加1
number += 1
#如果number模运算不等于0则打印
if number % 2 != 0 :
print(number)
print("*" * 20)
#10以内的偶数
prompt = "Enter a number "
#初始变量number为0
number = 0
#使用while循环直至number小于10
while number < 10 :
#number循环一次加1
number += 1
#如果模运算不等于0则使用continue继续循环
if number % 2 != 0 :
continue
print(number)
1
3
5
7
9
2
4
6
8
10
6、在循环中使用pass
- 只是占位符,代表什么都不做,没有跳过功能
#pass案例1
age = 16
if age > 18 :
pass
else :
print(str(age) + "小于18")
print("*"*20)
#pass不具有跳过功能
age = 18
if age >= 18 :
pass
print(str(age) + "大于等于18")
else :
print(str(age) + "小于18")
16小于18
18大于等于18
7、避免无限循环
- 每个while循环都必须有停止运行的途径,这样才不会没完没了地执行下去
- 程序陷入无限循环,可按Ctrl + C,也可关闭显示程序程序的终端的窗口
#定义变量number的初值为1
number = 1
while number < 5 :
print(number)
#如果不小心遗漏了代码行number += 1,程序无限循环
#number的初值为1,但根本不会变,因此条件测试始终为True
number += 1
1
2
3
4
二:使用while循环来处理列表和字典
- 到目前为止,我们每次都只处理了一项用户信息:获取用户的输入,再将输入打印出来或作出回答;循环再次运行时,我们获悉另一个输入值并作出响应。然而,要记录大量的用户和信息,需要在while循环中使用列表和字典
- for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其他元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示
1、在列表之间移动元素
- 假设有一个列表,其中包含新注册但未验证的网站用户
- 验证这些用户后,使用while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另外一个已验证用户列表中
#创建一个未验证用户的列表
unconfirmed_users = ['jack','kevin','tony']
#创建一个空列表,用于存储已验证的用户
confirmed_users = [ ]
#使用while不断循环,直至未验证用户列表为空
while unconfirmed_users :
#调用函数pop()从不断删除未验证用户列表的末尾
#将已验证的用户存储到current_users中
current_users = unconfirmed_users.pop()
print("Verifying : " + current_users.title())
#将已验证的用户存储到列表confirmed_users中
confirmed_users.append(current_users)
print("\nThe following users have been confirmed : ")
#遍历已验证用户的列表
for confirmed_user in confirmed_users :
print(confirmed_user.title())
Verifying : Tony
Verifying : Kevin
Verifying : Jack
The following users have been confirmed :
Tony
Kevin
Jack
2、删除包含特定值的所有列表元素
- 删除的值在列表中出现一次,可使用方法remove()来删除列表中的特定值
- 如果要删除列表中所有包含特定值的元素,可使用while循环
fruits = ['apple','banana','pear','apple']
while 'apple' in fruits :
fruits.remove('apple')
print(fruits)
[‘banana’, ‘pear’]
3、使用用户输入来填充字典
- 可使用while循环提示用户输入任意数量的信息
- 将收集的数据存储在一个字典中,以便将回答同被调查者关联起来
- 遇到的问题:
- 当被调查者输入两个及两个以上的水果如何存储在字典中
#定义一个空字典,用来存储收集的数据
name_fruits = { }
#定义一个标志位,设置为True
active = 'True'
#位True时就执行while循环
while active :
name = input("\nWhat is you name ? ")
fruit = input("What is you favorite fruit ? ")
#将收集的信息存储到字典中
name_fruits[name] = fruit
#询问用户调查是否继续
con = input("Would you like to another person respond(yes / no)")
#如果输入的是no,标志位将变为False
if con == 'no' :
active = 'False'
#使用break退出循环
break
#调查结果
print("\n---Poll Results---")
print(name_fruits)
#遍历字典中的键-值对
for na , fru in name_fruits.items():
print(na.title() + " favorite fruit is " + fru + ".")
What is you name ? jack
What is you favorite fruit ? apple
Would you like to another person respond(yes / no)yes
What is you name ? tony
What is you favorite fruit ? banana
Would you like to another person respond(yes / no)no
—Poll Results—
{‘jack’: ‘apple’, ‘tony’: ‘banana’}
Jack favorite fruit is apple.
Tony favorite fruit is banana.
小结
- 如何在程序中使用input()来让用户提供消息
- 如何处理文本和数字的输入,以及如何使用while循环让程序按用户的要求不断地运行
- 多种控制while循环流程的方式:
- 设置活动标志位、使用break语句以及使用continue语句
- 如何使用while循环在列表之间移动元素,以及如何从列表中删除所有包含特定值的元素
- 如何结合使用while循环和字典
本文介绍了Python中input函数和while循环的使用。input函数可让程序暂停等待用户输入,还能使用int()获取数值输入。while循环会不断运行,直到条件不满足。文中还介绍了控制while循环流程的多种方式,以及如何结合列表和字典使用while循环。
398

被折叠的 条评论
为什么被折叠?



