Python基础知识学习_input()函数和while循环

Python基础知识学习_input()函数和while循环

1、input()函数

1.1 input()函数工作原理

让程序暂停运行,等待用户输入一些文本
然后将其存在变量里面或者在屏幕上直接打印

用途:交互式程序

1.2 简单例子

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: Hello,
Hello,

1.2 编写简单程序

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

结果:

Please enter your name: wangping
Hello,wangping!

1.2.1 # 当提示超过一行时,将提示存储到一个变量中,再将该变量传递给函数input()

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

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

结果:

If you tell us who you are, we can peronalize the messages you see.
What is your first name?wang

Hello, wang!

1.3 数字比较,使用int()函数将输入字符串强制转为整形

str强制转为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? 155

You're tall enough to ride!

1.4 求模运算%(即,求余数)

作用:区分奇偶数(偶数能被2整除,余数为0;奇数不能为0整除,余数不为0),或者其他运算过程中需要用到余数的场合

4 % 3
5 % 3
6 % 3
7 % 3

结果:

Out[25]: 1
Out[26]: 2
Out[27]: 0
Out[28]: 1

1.4.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: 65

The number 65 is odd.

2、while循环

while循环与for循环的区别

while循环:在满足条件的情况下不断运行,直到不满足条件结束

for循环:用于针对集和中的每一个元素都一个代码块。

2.1 while 循环的应用(打印,执行运算)

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

结果:

1
2
3
4
5

2.2 让用户选择何时退出(人机互动)

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. Hello,everyone
Hello,everyone


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

2.3while 循环退出的方法

2.3.1 在while语句中使用条件测试来结束循环

age = input("\nHow old are you? ")
while age != 0: # 条件测试语句
    age = int(age)
    if age < 3:
        print("免费,不要钱")
       
    elif age < 12:
        print("$10")
    else:
        print("$15") 
    age = age -age

结果:

How old are you? 36
$15

2.3.2 使用标志退出循环(即使用一个变量:判断整个程序是否处于活动状态,这个变量被称为标志)

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. hell,liming
hell,liming


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

2.3.3 使用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 # 满足city == 'quit 条件,用break退出循环

结果

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


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

2.4 在循环中使用continue

执行机理:要返回循环开头,并根据条件测试结果决定是否继续执行循环

应用领域:

1、过滤偶数,选择奇数

2、过滤奇数,选择偶数

其他后面在补充

2.4.1、过滤偶数,选择奇数

理解:continue:当条件满足时,忽略continue后面代码,返回到程序循环的开始处

当条件不满足时,执行continue后面的代码

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

结果

1
3
5
7
9

2.4.2、过滤奇数,选择偶数

current_number = 0
while current_number < 100:
    current_number += 1
    if current_number % 2 != 0: 
        continue
    
    print(current_number)

结果

2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100

2.5 避免无限循环,即没有循环结束条件

案例

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

结果:

1
1
1
.
.

3、使用while循环:处理列表和字典

用途:

1、修改列表

2、移出重复的元素

3、存储数据(列表和字典),即记录大量信息

将while循环同列表和字典结合起来使用可以搜集、存储并组织大量输入,供以后查看和显示

while循环和for循环处理列表和字典的区别

for循环是遍历列表的有效方式,但在for循环中不应该修改列表(可以创建副本或者临时变量)

否则导致Python难以跟踪其中的元素

while循环:在遍历列表的同时可以对其进行修改

3.1、修改列表,即在两个列表之间移动

首先创建一个待验证用户列表

和一个用于存储已验证用户的空列表

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

3.2、移出重复的元素 (即删除所有重复元素)

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

print("初始pets集和为: ",pets)

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

print("去重后pets集和为:",pets)

结果

初始pets集和为:  ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
去重后pets集和为: ['dog', 'dog', 'goldfish', 'rabbit']

3.3、存储数据(列表和字典),即记录大量信息

使用用户输入来填充字典

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

结果

What is your name? Lishi

Which mountain would you like to climb someday? taishang

Would you like to let another person respond? (yes/ no)yes


What is your name? lioujing

Which mountain would you like to climb someday? yueshang

Would you like to let another person respond? (yes/ no)no

----------Poll Results -----------
Lishi Would like to climb taishang.
lioujing Would like to climb yueshang.
总结:
一、input()函数作用及其注意事项:

作用:将用户从输入设备(键盘,手机等等移动设备)输入的信息存储或者打印在屏幕上面,例如结合列表或者字典,实现列表元素的修改,以及实现字典来存储调查信息
注意事项:1、需要将输入值与数字量对比时,需要使用int()函数强制将字符串转为整形,否则出错
2、当提示信息太长时,可以将提示信息部分存储到变量中,然后在用变量加字符串拼接技术将后部分提示信息和前一部分信息拼接起来,最后将提示信息传给input函数

二、while循环作用以及其停止循环的方式

作用:1、修改或者移动列表中的元素
2、存储调查对象的信息,并打印
停止循环方式:1、while 后面跟上测试停止条件
2、使用标准变量
3、使用break语句

三、continue语句作用

作用:满足条件,跳过continue语句后面的语句,返回循环开头;不满足条件,执行continue后面的语句,故可以结合while语句来过滤数据

你可能感兴趣的:(笔记,python,学习,开发语言)