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

相关文章
|
8天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
1天前
|
机器学习/深度学习 数据可视化 数据挖掘
《Python 简易速速上手小册》第9章:数据科学和机器学习入门(2024 最新版)
《Python 简易速速上手小册》第9章:数据科学和机器学习入门(2024 最新版)
5 1
|
1天前
|
安全 数据处理 开发者
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
6 1
|
1天前
|
人工智能 数据挖掘 程序员
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
15 0
|
1天前
|
API Python
Python模块化编程:面试题深度解析
【4月更文挑战第14天】了解Python模块化编程对于构建大型项目至关重要,它涉及代码组织、复用和维护。本文深入探讨了模块、包、导入机制、命名空间和作用域等基础概念,并列举了面试中常见的模块导入混乱、不适当星号导入等问题,强调了避免循环依赖、合理使用`__init__.py`以及理解模块作用域的重要性。掌握这些知识将有助于在面试中自信应对模块化编程的相关挑战。
17 0
|
3天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
25 0
|
3天前
|
程序员 索引 Python
06-python数据容器-set(集合)入门基础操作
06-python数据容器-set(集合)入门基础操作
|
6天前
|
开发者 索引 Python
实践:如何使用python在网页的表格里抓取信息
实践:如何使用python在网页的表格里抓取信息
|
11月前
|
C++ Python
Python入门学习(1)
Python入门学习(1)
|
机器学习/深度学习 数据采集 人工智能
Python入门学习
每一种语言都有各自的思想和优势。或许了解一下,在进行本行的工作时,难免就会想起其他语言的解决方法。何况是人工智能语言非常广泛的python呢
Python入门学习

热门文章

最新文章