Python编程入门到实践 - 笔记( 7 章)

简介:

第 7 章讲了用户输入 input( ) 和 while 循环,内容如下

input( ) 工作原理

超过一行的 input( )

int( ) 来获取数字的输入,进行比较

求模运算

简单的 while 循环。我自己的理解就是设定一个条件,while 满足这个条件开始循环,不满足退出

break 直接退出

continue 跳出当前层的循环

避免无限循环

while 在列表中的应用

while 删除列表中指定的字符串 remove()

用户输入的字符来填充字典



input( ) 工作原理

首先定义 input( ) 函数括号中向用户显示提示说明,让用户输入内容

在将用户输入的内容保存到变量 message 中,最后打印

-------------------------------------------------------------------------------------------

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

-------------------------------------------------------------------------------------------

Tell me something, and I will repeat it back to you: haha   
haha



编写清晰的程序

---------------------------------------------------------

name = input("Please enter your name: ")   
print("Hello, " + name + "!")

---------------------------------------------------------

Please enter your name: python   
Hello, python!



超过一行的 input

如果想打印多行提示信息,可以使用 +=

-------------------------------------------------------------------------------------------

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

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

-------------------------------------------------------------------------------------------

If you tell us who you are, we can personalize the message you see.   
What is your first name? python

Hello, python!



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

如果不指定 age=int(age),python将会报错

-------------------------------------------

age = input("How old are you? ")   
print(age)

age = int(age)

if age >= 18:   
     print(age)

-------------------------------------------

How old are you? 29   
29    
29

 


int( ) 进行数值比较,进行测试

--------------------------------------------------------------------------------

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.")

--------------------------------------------------------------------------------

How tall are you, in inches? 89

You're tall enough to ride!



求膜运算符

两个数相除,返回余数

---------------------

print(4 % 3)   
print(5 % 3)    
print(6 % 3)    
print(7 % 3)

----------------------

1   
2    
0    
1



可以利用求模来计算一个数是奇数还是偶数

-------------------------------------------------------------------------------------------

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.")

-------------------------------------------------------------------------------------------

Enter a number, and I'll tell you if it's even or odd: 78

The number 78 is even.



while 循环

如果 while 小于等于 5,就一直运行

打印一次后,就将 current_number 的数值 +1

--------------------------------------

current_number = 1   
while current_number <= 5:    
     print(current_number)    
     current_number += 1

--------------------------------------

1   
2    
3    
4    
5



让用户选择何时退出

如果用户不输入 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)    
     print(message)

-------------------------------------------------------------------------------------

Tell me something, and I will repeat it back to you:   
Enter 'quit' to end the program. zhao    
zhao


Tell me something, and I will repeat it back to you:   
Enter 'quit' to end the program. shanshan    
shanshan


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



进行更改

上面的程序在用户输入 quit 时,也会将 quit 作为消息在打印一遍

代码中并没有定义如果用户输入 quit 会怎么样,所以当用户输入 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)

-------------------------------------------------------------------------------------

Tell me something, and I will repeat it back to you:   
Enter 'quit' to end the program. zhao    
zhao


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



继续改进上面的代码

就像刚才说的,并没有指定如果用户输入 quit 会怎么样

其实在 while 循环中嵌套一个 if-else 语句就可以了

但是开始循环时,先定义一个 active=True

如果是 True 就循环,是 False 就停止循环

------------------------------------------------------------------------------------

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)

------------------------------------------------------------------------------------

Tell me something, and I will repeat it back to you:   
Enter 'quit' to end the program. zhao    
zhao


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



break 直接退出循环

还是以上面的代码为例,当用户输入 break 时,直接 break,结束当前的 while 循环

-----------------------------------------------------------------------------------

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() + "!")

-----------------------------------------------------------------------------------

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


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


Please enter the name of a city you have visited:   
(Enter 'quit' when you are finished.)quit



continue 跳出当前的循环

每循环一次就 +1,当 current_number 可以被 2 整除的时候

就执行 continue,跳出这一层循环,继续 while 的下一次循环

------------------------------------------

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

     print(current_number)

------------------------------------------

1   
3    
5    
7    
9



避免无限循环

死循环代码如下,x 开始等于 1,在第一次循环结束后并没有变,

一直等于 1,永远满足  x <= 5 的条件,所以会被一直打印

------------------

x = 1   
while x <= 5:    
     print(x)

------------------


正常代码

需要指定一个条件,每循环一次 x 的值都 +1

------------------

x = 1   
while x <= 5:    
     print(x)    
     x += 1

------------------



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)    
     
print("\nThe following users have been confirmed:")    
for confirmed_user in confirmed_users:    
     print(confirmed_user.title())

-----------------------------------------------------------------------

Verifying user: Candace   
Verifying user: Brian    
Verifying user: Alice


The following users have been confirmed:   
Candace    
Brian    
Alice



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

while 中一直执行 remove( ) 删除列表中的 cat 字符

----------------------------------------------------------------------

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

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

print(pets)

----------------------------------------------------------------------

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



用户输入来填充字典

定义一个空的字典 responses

定义 polling_active = True 开始循环,等于 False 退出循环

让用户分别输入 name,response

responses[name] = response  将用户输入的添加到 responses 字典中

for 循环 items( ) 遍历 responses 字典

-------------------------------------------------------------------------------------------

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 respind? (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 + ".")

-------------------------------------------------------------------------------------------

What is your name? shanshan   
Which mountain would you like to climb someday? taiqiu     
Would you like to let another person respind? (yes/ no) no


--- Poll Results ---   
shanshan would like to climb taiqiu .

本文转自   mlwzby   51CTO博客,原文链接:http://blog.51cto.com/aby028/1965223

相关文章
|
1月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
288 7
|
1月前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
177 3
|
1月前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
406 3
|
1月前
|
Cloud Native 算法 API
Python API接口实战指南:从入门到精通
🌟蒋星熠Jaxonic,技术宇宙的星际旅人。深耕API开发,以Python为舟,探索RESTful、GraphQL等接口奥秘。擅长requests、aiohttp实战,专注性能优化与架构设计,用代码连接万物,谱写极客诗篇。
Python API接口实战指南:从入门到精通
|
1月前
|
存储 数据采集 监控
Python定时爬取新闻网站头条:从零到一的自动化实践
在信息爆炸时代,本文教你用Python定时爬取腾讯新闻头条,实现自动化监控。涵盖请求、解析、存储、去重、代理及异常通知,助你构建高效新闻采集系统,适用于金融、电商、媒体等场景。(238字)
309 2
|
1月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
257 3
|
1月前
|
存储 Java 调度
Python定时任务实战:APScheduler从入门到精通
APScheduler是Python强大的定时任务框架,通过触发器、执行器、任务存储和调度器四大组件,灵活实现各类周期性任务。支持内存、数据库、Redis等持久化存储,适用于Web集成、数据抓取、邮件发送等场景,解决传统sleep循环的诸多缺陷,助力构建稳定可靠的自动化系统。(238字)
475 1
|
1月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
241 0
|
机器学习/深度学习 人工智能 Python
|
2月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
280 102