美文网首页
Python学习笔记5—用户输入和while循环

Python学习笔记5—用户输入和while循环

作者: 肉松饼饼 | 来源:发表于2017-12-17 14:44 被阅读0次

一、用户输入

1、函数input()的工作原理

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。函数input()接受一个参数,即要向用户显示的提示或说明,让用户知道该怎么做。

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

注:提示末尾(这里是冒号后面)包含一个空格,可将提示和用户输入分开,让用户清楚知道其输入始于何处。

message = "Tell me something,and I will repeat it back to you."
message += "\nNow what do you want to say? "
prompt = input(message)
print(message)

注:上述代码展示了提示超过一行的处理方法,将提示存储在一个变量中,再将这个变量传递给函数input()。

2、使用int()来获取数值输入

使用函数input()时,Python将用户输入解读为字符串。将数值输入用于计算和比较时,务必将其转换为数值表示。

number = input("Enter a number,and I will 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.")

注:求模运算符%常用来判断一个数的奇偶性。

3、在Python 2.7中获取输入

应使用raw_input()来提示用户输入,也将输入解读为字符串。

二、while循环

for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
1、使用while循环

prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
#使用标志
active = True
while active:
    messsage = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

注:在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志,充当了程序的交通信号灯。程序在标志位True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。这样,在while语句中就只需要检查一个条件——标志的当前值是否为True,并让所有测试(是否发生了应将标志设置为False的事件)都放在其他地方,从而让程序变得更为整洁。

2、退出循环

  • break 退出循环,不再运行循环中余下的代码
  • continue 退出当前循环,返回循环开头

注:应避免无限循环,若程序陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口。

3、使用while循环来处理列表和字典

for循环时一种遍历列表的有效方法,但在for循环中不应修改列表,否则会导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将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)

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

pets = ['dog','cat','rabbit','cat','cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

③ 使用用户输入来填充字典

responses = []
#设置一个标志,指出调查是否继续
polling_active = True

while pollint_active:
    #提示输入被调查者的姓名和回答
    name = input("\nWhat is your name? ")
    responses = input("\nWhich color would you like best? ")

    #将答案存储在字典中
    responses[name] = responses

    #看看是否还有人要参与调查
    repeat = input("Would 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 + " like " + response +" best!")

相关文章

网友评论

      本文标题:Python学习笔记5—用户输入和while循环

      本文链接:https://www.haomeiwen.com/subject/whjywxtx.html