当前位置:   article > 正文

Python编程 从入门到实践 第七章 用户输入和while循环_python编程从入门到实践 第7章节

python编程从入门到实践 第7章节

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

  1. 函数input()让程序暂停运行,等待用户输入内容,并在用户输入完按回车键后继续运行;
  2. 获取用户输入后,Python将其存储在一个变量中。
message = input("Tell me something,and I will repeat it back to you: ")
print(message)
  • 1
  • 2
Tell me something,and I will repeat it back to you: Hello everyone!
Hello everyone!
  • 1
  • 2

1.1 编写清晰的程序

  1. 下面第一行代码 name: 后面包含一个空格,可将提示与用户输入分开;
name = input("Please enter your name: ")
print("Hello, " + name + "!")
  • 1
  • 2
Please enter your name: Eric
Hello, Eric!
  • 1
  • 2
  1. 当提示超过一行吗,可将提示存储在一个变量中,再将变量传递给函数input();
  2. 运算符 += 表示在存储在prompt中的字符串末尾附加一个字符串;
  3. 下面第二行代码 name? 后面包含一个空格,同上也是出于清晰考虑。
prompt = "If you tell us who you are,we can personalize the messages you see."
prompt += "\nwhat is your name? "

name =input(prompt)
print("\nHello," + name +"!")
  • 1
  • 2
  • 3
  • 4
  • 5
If you tell us who you are,we can personalize the messages you see.
what is your name? Eric

Hello,Eric!
  • 1
  • 2
  • 3
  • 4

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

  1. 使用函数input()时,Python默认将用户输入变为字符串;
  2. 下面代码输出结果21用引号括起来了;
>>> age = input("How old are you? ")
How old are you? 21
>>> age
'21'
  • 1
  • 2
  • 3
  • 4
  1. 字符串的输出结果不能与数值进行比较,会报错;
>>> age = input("How old are you? ")
How old are you? 21
>>> age >= 18
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  1. 为解决上述问题,可使用函数int(),Python将转换为数值;
>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 演示示例如下:
height = input("How tall are you,in inches? ")
height = int(height)
if height >= 36:
    print("\nYou're tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a little older.")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
How tall are you,in inches? 71

You're tall enough to ride!
  • 1
  • 2
  • 3

1.3 求模运算符

  1. % 是将两个数相除并返回余数;
  2. 如果一个数可被另一个数整除,余数就是0,取模运算符将返回0;
  3. 可利用取模结果是否为0判断一个是是否为奇数(odd)或是偶数(even);
  4. == 是相等运算符;
  5. 演示示例如下:
number = input("Enter a number,and I'll 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.")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
Enter a number,and I'll tell you if it's even or odd: 42

The number 42 is even.
  • 1
  • 2
  • 3

2. while循环

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

2.1 使用while循环

  1. 演示示例如下:
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
  • 1
  • 2
  • 3
  • 4
1
2
3
4
5
  • 1
  • 2
  • 3
  • 4
  • 5

2.2 让用户选择何时退出

  1. 演示示例如下:
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)
    print(message)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
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
quit
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  1. 上述代码最后一行将quit也进行了输出,对代码进行优化:
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.3 使用标志

  1. 在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,类似于程序中的交通信号灯,这个变量称为标志;
  2. 下面的演示示例中 active 为标志名(可给它指定任一名)
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.4 使用 break 退出循环

  1. break语句:立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何
  2. break语句用于控制程序流程
  3. 演示示例如下:
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() + "!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) New York
I’d love to go to New York!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) San Francisco
I’d love to go to San Francisco!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.5 在循环中使用 continue

  1. continue语句:返回到循环开头,并根据条件测试结果决定是否继续执行循环
  2. 不像break语句那样:不再执行余下的代码并退出整个循环
  3. 演示示例如下:
current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
1
3
5
7
9
  • 1
  • 2
  • 3
  • 4
  • 5

2.6 避免无限循环

  1. 每个while循环都必须有停止运行的途径
  2. 如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口
  3. 演示实例如下:
#正确代码
x = 1
while x <= 5:
    print(x)
    x += 1
  • 1
  • 2
  • 3
  • 4
  • 5
#无限循环代码
x = 1
while x <= 5:
    print(x)
  • 1
  • 2
  • 3
  • 4

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

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

3.1 在列表之间移动元素

  1. 演示示例如下:
#首先,创建一个待验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice','brain','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())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
Verifying user: Candace
Verifying user: Brain
Verifying user: Alice

The following users have been confirmed:
Candace
Brain
Alice
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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

  1. 演示示例如下:
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)
  • 1
  • 2
  • 3
  • 4
  • 5
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
  • 1
  • 2

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

  1. 可使用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 Results ---")
for name,response in responses.items():
    print(name + " would like to climb " + response + ".")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
what is your name? Eric
which mountain would you like to climb someday? Denali
Would 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
Would you like to let another person respond?(yes/no)no

--- poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thumb.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4. 章节跳转

  1. Python编程 从入门到实践 第一章 起步
  2. Python编程 从入门到实践 第二章 变量和简单数据类型
  3. Python编程 从入门到实践 第三章 列表简介
  4. Python编程 从入门到实践 第四章 列表操作
  5. Python编程 从入门到实践 第五章 if语句
  6. Python编程 从入门到实践 第六章 字典
  7. Python编程 从入门到实践 第七章 用户输入和while循环
  8. Python编程 从入门到实践 第八章 函数
  9. Python编程 从入门到实践 第九章 类
  10. Python编程 从入门到实践 第十章 文件和异常
  11. Python编程 从入门到实践 第十一章 测试代码
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/640713
推荐阅读
相关标签
  

闽ICP备14008679号