Python学习笔记

十五、用户输入和while 循环

2017-11-18  本文已影响34人  焰火青春

1、用户输入和while 循环

大多数程序旨在解决最终用户问题,在程序要一个名字时,需要提示用户输入名字,需要名单时,输入一系列名字,为此需要用到input()函数,来获取用户的输入。

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

它可以使程序停止,等待用户输入,待输入后,将信息存储到一个变量中,以方便程序使用:

msg = input('Tell me something, i will repeat it back to you :')
print(msg)

----
输入'Hello World!'
打印出:
Tell me something, i will repeat it back to you :Hello World!
Hello World!

1.1.1、编写清晰的程序

提醒用户输入的提示信息,可以是一行也可以是多行,当是多行时,可使用字符串分行书写:

msg = 'If you tell us who you are, we can personalize the message you see.'
msg += "\nWhat's you first name? "       # 将后一段提示添加到字符串后面,阅读起来更清晰
name = input(msg)
print('\nHello ' + name + '!')

-------
Tell me something, i will repeat it back to you. 
What's you first name? eric

Hello, Eric!

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

使用input()函数,python解读的时字符串,有时需要用到数字时,就要用到int()函数了,它可以将字符串转换成整型。

>>> age = input('how old are you? ')
how old are you? 21        # 获得是字符串,显然不符合需求
>>> age
'21'
>>> age = int(input('how old are you? '))  # 在input()前加一个int()函数,将字符串转换成整型
how old are you? 21
>>> age
21

1.1.3、求模运算符(%)

求模运算符(%),指的是求两个数的余数,利用此可以判断这个数是奇数还是偶数:

num = int(input('enter a number, i will tell you this number is even or odd: '))
if num % 2 == 0:   # 如果这个数除以2,余数为0则为偶数,否则为奇数
    print('this number ' + str(num) + ' is a even.')  # 数字和字符串不能直接相连接,数字要转换成字符串
else:
    print('this number ' + str(num) + ' is a odd.')

enter a number, i will tell you this number is even or odd: 23
this number 23 is a odd.

1.2、while 循环

for循环可以用来遍历字典、列表、元组等中的每个元素,if语句只能每次执行一次,而while循环可以重复循环,直至达到满足条件为止。

1.2.1、使用while 循环

while 循环,首先判断条件是否为真,真则执行循环体,假则结束循环:

# 利用while 循环数数
current_num = 1
while current_num <= 5:  # 只要current_num <= 5,程序就会继续循环下去,直至大于5
  print(current_num)
  current_num += 1

1.2.2、让用户选择何时退出

while 循环可以使程序不断运行下去,直至条件为假(用户想要它停止时),如下,我们定义了一个退出值,可以结束循环:

# 定义了一个退出值(quit)
prompt = '\nTell me something, I will repeat it back to you:'
prompt += "\nEnter 'quit' to end of program. "
msg = ''
while msg != 'quit':     # 当用户输入的不是quit时循环执行,打印信息,当是quit时循环终止
  msg = input(prompt)
  
  if msg != 'quit':
    print(msg)
-----------------------------    
Tell me something, and i will repeat it back to you:
Enter 'quit' to end of program.hello world
hello world

Tell me something, and i will repeat it back to you:
Enter 'quit' to end of program.
  

1.2.3、使用标志

我们可以让程序在指定条件下运行,但在更加复杂的程序中,很多事件能导致程序停止运行,这种情况下不可能使用很多条while语句去检查所有条件,即增加了代码量也不便于阅读,这时我们可以定义一个变量,用来判断程序是否处于活动状态,这个变量称为标志,为True时,程序继续运行,并在任何事件导致的值为False时让程序停止运行,这样while只需检查一次条件即可。

prompt = '\nTell me somethin, I will repeat it back to you:'
prompt += "\nEnter 'quit' to end of program. "
active = True           # 首先定义一个变量,初始值为True,while才能运行,变量名随意

while active:                         
  msg = input(prompt)
  
  if msg == 'quit':            # 当用户输入quit时,变量active变为False,循环终止
    active = False
  else:
    print(msg)

1.2.4、使用break 退出循环

要立即退出while 循环,不再运行循环中余下代码,也不管条件测试结果如何,可使用break。

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() + '.')
print('Down!')  # break语句跳出循环后执行该条语句

1.2.5、在循环中使用continue

continue语句可以中止当前循环,跳到循环开头,进行下一次循环,在进行循环的时候会检查循环条件:

current_num = 0 
while current_num < 10:
  current_num += 1
  if current_num % 2 == 0:  # 当为偶数时,求模为0,中止当前循环,跳到循环开头,重新判断条件
    continue
  print(current_num)  # 如果不能被2整除,则执行余下代码
1
3
5
7
9

1.2.6、避免无限循环

每个while循环必须有停止运行的途径,这样才不会一直执行下去,要避免死循环,应该对while循环进行测试;如果希望程序在用户输入特定值时结束,可运行程序并输入这样的值,如果在这种情况下程序没有结束,则要检查程序处理这个值的方式,至少保证有一个这样的地方能让循环条件False或让break语句得以执行。

当进行死循环时可以按ctrl + c 停止:

x = 1           # 由于x的值是个常量,一直小于5,程序进入死循环
while x < 5:
    print(x)

练习

# 电影票根据年龄来收取价格,首先询问顾客年龄
prompt = '\nHow old are you?'
prompt += "\nEnter 'quit' when you finished. "

while True:
  age = input(prompt)
  if age == 'quit':     # 如果谷歌输入quit则跳出循环
    break
  age = int(age)          # 由于input()函数python接收的是字符串,需要转换成数字
  if age < 3:
    print('You get in free!')
  elif 3 <= age <= 12:
    print('You ticket is 10$.')
  else:
    print('You ticket is 15$.')
  

  

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

要记录大量的用户和信息,需要在while 循环中使用列表和字典,for 循环遍历列表难以跟踪其中的元素,要在遍历的同时对其进行修改,可使用while 循环,通过将while 循环同列表和字典结合起来使用,可收集、存储并组织大量输入,以供查看和显示。

1.3.1、在列表间移动元素

假设有个列表,包含注册但未验证的用户,验证后将他们移动到一个已经验证过的列表中:

uncofirmed_users = ['alice', 'brian', 'candace']  # 未验证
confirmed_users = []        # 创建一个验证过的用户空列表

while uncofirmed_users:        # 循环一直运行,直到列表为空
  current_users = unconfirmed_users.pop()  # 弹出列表最后一个元素,把它存储到变量xxx中
  print('Verfying users: ' + current_users.title())  
  confirmed_users.append(current_users)   # 把这个变量存储到空列表中
  
print('\nThe following users have been confirmed:')  
for confirmed_user in confirmed_users:  # 遍历第二个列表
  print(confirmed_user)
-------------------------------------  
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice

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

在列表中我们学习了如何用remove()删除列表中的特定值,但是它只能删除列表中同种元素的第一个值,其他的不能删除。

# 一个包含很多宠物的列表,要删除里面所有的cat
pets = ['dogs', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:  # 进入循环后,发现'cat'在列表至少存在一次,python删除第一个'cat',并返回到while代码行,发现还有'cat',继续删除,直到删除所有为止
  pets.remove('cat')
print(pets)
------

['dogs', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dogs', 'dog', 'goldfish', 'rabbit']

1.3.3、使用用户输入来填充字典

可使用while 循环来提示用户输入任意数量的信息

# 创建一个调查程序,记录调查者的名字,喜欢的山,并将数据存储到一个字典中
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 respond? (Yes/ No)')
    # 如果没有则标志的值为假,循环中止
    if repeat == 'No':
        polling_active = False
# 打印结果,显示结果        
print('\n--- Poll Result ---')
for name, response in responses.items():
    print(name + ' would like to climb ' + response + '.')
--------------------------------

What is your name? alice
Which mountain would you like to climb someday? denali
Would you like to let another person respond? (Yes/ No)No

--- Poll Result ---
alice would like to climb denali.

关于上面的这个例子是如何将名字和回答添加到字典中

>>> responses = {}
>>> name = 'alice'
>>> response = 'denali'
>>> responses[name] = response           # 字典名+[存储键的变量] = 存储值的变量
>>> print(responses)                    # 区别于访问字典中的值,responses['alice']
{'alice': 'denali'}
上一篇下一篇

猜你喜欢

热点阅读