Python基础知识7——用户输入和while循环

本章内容来自书籍,记录下来仅方便复习,如有侵权,请联系作者删除。

通过获取用户输入并学会控制程序的运行时间,可写出交互式程序

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

使用规则: message = input("提示语")
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python以字符串的形式,将其输入的数据存储在一个变量之中。小括号中可以输入提示语

message = input("please enter a data: ")
print("The data is: "+message)
运行结果
please enter a data: 333
The data is: 333

1. 编写清晰的程序
使用函数input()时,应该指定清晰而明白的提示。当提示超过一行时,先将提示语存储在一个变量中,再将变量传递给函数input()

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print("\nHello, "+name.title()+"!")

运行结果
If you tell us who you are, we can personalize the messages you see.
What is your first name? eric

Hello, Eric!

2. 使用函数int()来获取数值输入
函数input()会返回一个字符串,如果传入一个数值,直接使用会报错,需要用函数int()将其转换成数值,才可以使用。

未使用int()转换数值:

age = input("How old are you? ")
if age > 18:
    print("You're an adult.")
else:
    print("You're a children.")
运行结果
How old are you? 12

TypeError: '>' not supported between instances of 'str' and 'int'

使用int()转换为数值:

age = input("How old are you? ")
age = int(age)
if age > 18:
    print("You're an adult.")
else:
    print("You're a children.")
运行结果
How old are you? 22
You're an adult.

将数值输入用于计算和比较前,务必先将其转换成数值表示。

3. 求模运算符
求模运算符(%)能将两个数相除并返回余数。
如利用求模运算符判断奇偶数:

number = input("Enter a number: ")
number = int(number)

if number%2 == 0:
    print("\nThe number " + str(number) + " is even.")
elif number%2 != 0:
    print("\nThe number "+ str(number) +" is odd.")

运行结果
Enter a number: 3

The number 3 is odd.

4. 在Python2.7中获取输入
Python2中输入函数:raw_input()
Python3中输入函数:input()

二、while循环简介

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

1. 使用while循环
简单规则:

while(条件测试):
	循环体

条件测试两边的括号可以省略,条件测试为真时,才运行循环体内的代码,循环体内的代码需要缩进。

简单例子:

number = 1
while(number <= 5):
    print(number)
    number += 1
运行结果
1
2
3
4
5

2. 让用户选择何时退出

方式:定义一个退出值,每循环一次,就询问一次。

如下所示,定义一个空字符串message,并设置退出值为"no",当代码执行到message = input(input_prompt)时,Python显示提示信息,并等待用户输入。只要用户没有输入退出值为"no",Python将再次执行while循环。当用户输入"no"时,Python停止执行while循环,程序结束。

message = ''
number = 1
while message != 'no':
    print("\nThis is a while loop: "+str(number))
    number += 1
    input_prompt = "\nYou can enter 'no' to end the program.\n"
    input_prompt += "Continue to cycle? "
    message = input(input_prompt)

运行结果
This is a while loop: 1

You can enter 'no' to end the program.
Continue to cycle? hello

This is a while loop: 2

You can enter 'no' to end the program.
Continue to cycle? hi

This is a while loop: 3

You can enter 'no' to end the program.
Continue to cycle? no

3. 使用标志
在前一个示例中,我们让程序在满足条件是就执行特定的任务,但是在更复杂的程序中,很多不同的事件都会导致程序停止运行,在这种情况下,该怎么办呢?

在要求很多条件满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,整个变量称为标志。

while语句中秩序检查该标志的当前值是否为True,将所有测试,应该将标志设置为True/False的事件放在其他地方。

接下来,我们将这个标志命名为active,它将用于判断程序是否应继续运行。

input_prompt = "\nYou can enter 'no' and 'quit' to end the program.\n"
input_prompt += "Continue to cycle? "

active = True
number = 1
while active:
    print("\nThis is a while loop: "+str(number))
    number += 1

    message = input(input_prompt)
    if message == 'no':
        active = False
    elif message == 'quit':
        active = False
    else:
        active = True

运行结果1:
This is a while loop: 1

You can enter 'no' and 'quit' to end the program.
Continue to cycle? lala

This is a while loop: 2

You can enter 'no' and 'quit' to end the program.
Continue to cycle? no

运行结果2:
This is a while loop: 1

You can enter 'no' and 'quit' to end the program.
Continue to cycle? haha

This is a while loop: 2

You can enter 'no' and 'quit' to end the program.
Continue to cycle? quit

在这里,我们设置了两个让程序停止的条件,如果用户输入’no’ 或者 ‘quit’,将active标志设置为False,循环退出。

4. 使用break退出循环
break语句,立即退出while循环,不在运行循环中余下的代码,也不管测试条件的结果如何。在任何Python循环中都可以使用break语句,包括for循环。

input_prompt = "\nYou can enter 'no' and 'quit' to end the program.\n"
input_prompt += "Continue to cycle? "

number = 1
while True:
    print("\nThis is a while loop: "+str(number))
    number += 1

    message = input(input_prompt)
    if message == 'no':
        break
    elif message == 'quit':
        break    

运行结果
This is a while loop: 1

You can enter 'no' and 'quit' to end the program.
Continue to cycle? dd

This is a while loop: 2

You can enter 'no' and 'quit' to end the program.
Continue to cycle? no

5. 使用continue
使用continue语句,可返回到循环开头,并根据条件测试结果决定是否继续执行循环。
例如,一个从1数到10,值打印偶数的循环:

number = 0
while number <= 10:
    number += 1
    if number%2 != 0:
        continue

    print(number)
 
运行结果
2
4
6
8
10

6. 避免无线循环
如果陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口。

要避免编写无限循环,务必对每个while循环进行测试,确保它按预期那样结束。

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

for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以继续跟踪其中的元素。要在遍历列表的同事对其进行修改,可使用while循环。通过while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。

1. 在列表之间移动元素
例子:模拟用户验证过程,两个用户列表,一个新注册但未验证列表register_users[],一个已验证列表confirmed_users[],要求验证所有的注册用户,并将验证过的用户移动到列表confirmed_users[]中。

register_users = ['neil','sam','alice','candace']
confirmed_users = ['brian']

while register_users:
    confirmed_user = register_users.pop()

    print("Verifying user: " + confirmed_user.title())
    confirmed_users.append(confirmed_user)

print("\nconfirmed users:")
print(confirmed_users)

运行结果:
Verifying user: Candace
Verifying user: Alice
Verifying user: Sam
Verifying user: Neil

confirmed users:
['brian', 'candace', 'alice', 'sam', 'neil']

2. 删除包含特定值的所有列表元素
删除方式:
列表中只有一个该特定值,则使用函数remove()来删除列表中的特定值
列表中有多个该特定值,则不断地运行一个while循环,将函数remove()放在循环体中,知道列表中不在包含该值。

例子:pets.py
删除宠物列表中的所有cat

pets = ['cat','dog','cat','goldfish','rabbit','cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')
print(pets)

运行结果
['cat', 'dog', 'cat', 'goldfish', 'rabbit', 'cat']
['dog', 'goldfish', 'rabbit']

3. 使用用户输入来填充字典
可使用while循环提示用户输入任意数量的信息。

user_infos = {}
polling_active = True

while polling_active:
    user_name = input("\nPlease enter your name: ")
    user_like = input("Please enter your favorite foot: ")
    user_infos[user_name] = user_like

    repeat = ''
    while repeat != 'no' and repeat != 'yes':
        repeat = input("Continue? (yes/no) ")

    if repeat == 'no':
        polling_active = False
    
print("-"*10+"Poll Results"+"-"*10)
# print(user_infos)
for name,like in user_infos.items():
    print(name +" like "+ like)

运行结果
Please enter your name: lynn
Please enter your favorite foot: apple
Continue? (yes/no) yes

Please enter your name: sam
Please enter your favorite foot: banana
Continue? (yes/no) yes

Please enter your name: neil
Please enter your favorite foot: orange
Continue? (yes/no) no
----------Poll Results----------
lynn like apple
sam like banana
neil like orange

四、 小结

学习了 input函数、处理文本和数字的输入、while循环,控制while循环,break语句和continue语句,使用while循环修改列表之间的元素,结合使用while循环和字典。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值