【Python编程入门】Lecture 7:用户输入和while循环

7.1 用户输入

7.1.1 input()函数

函数input()让程序暂停运行,等待用户输入后,将用户输入的文本以字符串的形式返回,该函数可以接受一个参数,这个参数是要向用户展示的提示(prompt)或说明,从而让用户明白应该输入什么。

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: 12345, climbing mountain and hunting tigers.
12345, climbing mountain and hunting tigers.

注意:
1、在提示语末尾打一个空格,可将提示语与用户输入分开,视觉效果较为清晰。
2、比较长的提示语,可以赋给一个变量,再通过该变量传递给input()函数。

prompt = "If you tell us who you are, we can perisonalize the message you see."
prompt += "\nWhat's your first name? "  #表示在字符串prompt末尾附加一个字符串
message = input(prompt)
print(f"Morning,{message}!")
If you tell us who you are, we can perisonalize the message you see.
What's your first name? YU
Morning,YU!

7.1.2 数值型输入

有时需要将用户输入的数值与某数进行比较,但是字符串格式的数字无法与数值进行比较,因此需要将用户输入转化为整数(int)或浮点数(float)格式。

1、int()函数
int() 函数用于将一个字符串或数字转换为整型。该函数可以具有两个参数int(x, base=10),第一个参数x是字符串或数字,第二个参数base是进制数,缺省默认十进制。

prompt = "How old are you? "
age = input(prompt)
if int(age) >= 18:
    print("You're an adult.")
else:
    print("You aren't an adult.")
How old are you? 18
You're an adult.

int()函数将浮点数以去尾法转换为整数。

print(int(2.6))
print(int(1.2))
2
1

2、float()函数
float() 函数用于将整数和字符串转换成浮点数。

print(float(2))
2.0

注意,以上两个函数都只能将本来就是数字的字符串转换为数值。

7.2 while循环

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

7.2.1 while循环简介

while循环的基本结构是
while 布尔表达式 :(冒号)
(缩进) 需要循环的操作

例如用while循环实现从1数到5的程序如下:

current_number = 1
while current_number <= 5 :
    print(current_number)
    current_number += 1  #代码 current_number = current_number + 1 的简写
1
2
3
4
5

1、避免无限循环
如果上述代码遗漏最后一行,则会陷入无限循环,不断输出1。在Sublime Text等编辑器中内嵌了输出窗口,这导致难以结束无限循环,此时可在输出窗口单机鼠标,然后按Ctrl+C以结束无限循环。

2、让用户选择何时退出
使用while循环在用户愿意的时候不断运行,只需定义一个退出值,只要用户输入不是这个值,循环就一直进行。如以下程序,实现了只要用户不输入“quit”,则一直计数的功能。

current_number = 1
prompt = "Enter anything to count numbers."
prompt += "\nEnter 'quit' to end the progranm: " 
message = ""
while message != 'quit' :
    message = input(prompt)
    print(current_number)
    current_number += 1
Enter anything to count numbers.
Enter 'quit' to end the progranm: quit
1

该程序第2行定义了一条提示消息,告诉用户要么退出,要么随便输入以数一个数。第4行创建了初始为空字符串的message变量,防止进入while循环时未定义message而报错。第5行为while循环,进入循环后提示用户输入,根据用户输入执行程序。注意,此处我们发现用户要求退出程序,但程序执行了一遍相应的操作才退出,对此我们可以加入一个if语句。

current_number = 1
prompt = "Enter anything to count numbers."
prompt += "\nEnter 'quit' to end the progranm: " 
message = ""
while message != 'quit' :
    message = input(prompt)
    if message != 'quit':
        print(current_number)
        current_number += 1
Enter anything to count numbers.
Enter 'quit' to end the progranm: q
1

Enter anything to count numbers.
Enter 'quit' to end the progranm: uu
2

Enter anything to count numbers.
Enter 'quit' to end the progranm: quit

这个程序在while循环中加入了if语句,在用户输入后紧接着根据if语句判断用户是否要求终止程序,不终止程序则执行相应的操作。

7.2.2 标志

在复杂的程序中,导致程序停止运行的事件会有很多,为此可定义一个用于判断整个程序是否处于活动状态的布尔变量,这个布尔变量称为标志(flag)。标志类似于交通信号灯,让程序在标志为True的时候继续运行,并在任何事件导致标志变为False后让程序停止运行。

current_number = 1
prompt = "Enter anything to count numbers."
prompt += "\nEnter 'quit' to end the progranm: " 
active = True
while active :
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(current_number)
        current_number += 1
Enter anything to count numbers.
Enter 'quit' to end the progranm: a
1

Enter anything to count numbers.
Enter 'quit' to end the progranm: quit

7.2.3 break语句

break语句用在while和for循环中,是用来终止循环语句的,即使循环条件没有变成False也会停止执行循环语句,并跳出break语句所在的最深层循环,开始执行该循环下一行的代码。

current_number = 1
prompt = "Enter anything to count numbers."
prompt += "\nEnter 'quit' to end the progranm: " 
while True :
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(current_number)
        current_number += 1
Enter anything to count numbers.
Enter 'quit' to end the progranm: quit

7.2.4 continue语句

continue用在while和for循环中,是用来跳出本次循环的,即跳过本轮循环的剩余语句,然后继续进行下一轮循环。以下例子输出1到10的所有奇数,虽然这个例子不用continue语句也可以实现。

current_number = 0
while current_number < 10 :
    current_number += 1  
    if current_number % 2 == 0 :    #复习2.4.1算术运算符 取模运算
        continue    #当前是偶数,跳过后面的语句,开始新一轮循环
    print(current_number)
1
3
5
7
9

7.3 使用while循环处理列表和字典

for循环是一种遍历列表的有效方式,但不应该在for循环中修改列表,不然会使得Python难以跟踪其中的元素。如果要在遍历列表的同时对其进行修改,可以使用while循环。将while循环与列表、字典结合起来使用,可以收集、存储并组织大量输入。

7.3.1 将列表中的元素移动到另一个列表中

假设有一个列表包含学生姓名,现在要检查作业,使用while循环,检查学生作业的同时将已被检查的学生姓名从列表中提取出来,并加入一个已检查作业学生名单。

unchecked_students = ['Alice','Bob','Carol']
cheched_students = []
while unchecked_students:
    current_student = unchecked_students.pop()
    print(f"Checking {current_student}'s homework")
    cheched_students.append(current_student)
print(cheched_students)
Checking Carol's homework
Checking Bob's homework
Checking Alice's homework
['Carol', 'Bob', 'Alice']

7.3.2 删除列表中所有的特定值元素

回顾3.2.5中的remove()方法。要使用remove()方法删除列表中所有的特定值元素,可以使用while循环。

subjects = ['Math','Englishi','Math','Chinese','Math']
print(subjects)
while 'Math' in subjects:
    subjects.remove('Math')
print(subjects)
['Math', 'Englishi', 'Math', 'Chinese', 'Math']
['Englishi', 'Chinese']

7.3.3 使用用户输入填充字典

假设现在要学生评选最喜欢的老师,询问每位学生的姓名及想要投票的老师,并将数据收集在字典中,同时在提示投票成功信息后询问是否还有哦其他学生想要参与投票。

favorite_teacher = {}
active = True
while active:
    student = input("What's your name? ")
    teacher = input("Who you want to vote for? ")
    weekend_class[student] = teacher
    print(f"{student}, you have voted for Prof.{teacher}.")
    repeat = input("Are there any orther students want to vote? Please answer 'yes' or 'no' : ")
    if repeat == 'no':
        active = False
print(favorite_teacher)
What's your name? Alice

Who you want to vote for? Yi HUANG
Alice, you have voted for Prof.Yi HUANG.

Are there any orther students want to vote? Please answer 'yes' or 'no' : yes

What's your name? Bob

Who you want to vote for? Yi HUANG
Bob, you have voted for Prof.Yi HUANG.

Are there any orther students want to vote? Please answer 'yes' or 'no' : no

{'Alice': 'Yi HUANG', 'Bob': 'Yi HUANG'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值