目录

一、函数 input() 的原理

1.1 编写清晰的程序

1.3 求模运算

二、while 循环简介

2.1 使用 while 循环

 2.2 让用户选择何时退出

 2.3 使用标志

2.4 使用 break 退出循环

2.5 在循环中使用continue

2.6 避免无限循环

练习

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

3.1 在列表之间移动元素

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

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


一、函数 input() 的原理

函数 input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,python将其存储在一个变量中,以方便使用。

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

print(message)

1.1 编写清晰的程序

input() 函数接受一个参数,可以向用户清晰且易于明白地指出希望用户输入的信息。

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

⚠️使用python3解释器,input()可以直接辨别输入的字符串,但是python2解释器输入字符串需要加“”.

pycharm默认了python2解释器。

已解决!

python当输入over停止输入 python直到用户输入over为止_python

在这里,添加python解释器

python当输入over停止输入 python直到用户输入over为止_字符串_02

python当输入over停止输入 python直到用户输入over为止_ci_03

设置运行文件时,选择解释器python3.7。


有时,提示语句可能超过一行,此时可将提示语句存储在一个变量中。

prompt = "If you tell us you are, we can personalize the message you see."
prompt +="\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name +"!")

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

使用函数 input() 时,python解释器将用户的输入解读为字符串格式。

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

<class 'str'>

使用函数 int() ,可以将数字的字符串表示转换为数值表示。

e.g.1 判断一个人是否满足坐过山车的身高。

height = input("How tall are you, in inches? ")
height = int(height)

if height>=36:
    print("\nYou are tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a little older.")

1.3 求模运算

求模运算符% :将两数相除并返回余数。

若一个数可被另一个数整除,余数为0,可利用这一点判断奇/偶数。

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

python 2.7中,使用 raw_input() 来获取用户输入,raw_input() 也将用户输入解读为字符串格式;

python 2.7也包含 input() ,将用户输入解读为python代码,并尝试运行;python 2.7下,最好使用 raw_input() 来获取用户输入。


二、while 循环简介

for 循环针对集合中的每一个元素都执行同一段代码;while 循环不断运行,知道满足指定的条件为止。

2.1 使用 while 循环

使用 while 循环计数。

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

 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)

 2.3 使用标志

在要求很多条件都满足时才继续运行程序时,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为标志。

while 循环只需要判断标志是否为"True",改变标志值的其他条件可以使用if 语句判断。

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)

2.4 使用 break 退出循环

  • 立即退出循环
  • 在任何Python循环中都可使用break语句。e.g. 可以使用break 退出遍历列表或字典的for循环。
prompt = "\nPlease enter the name of a city you have visited: "
prompt += "\nEnter 'quit' when you are finished. "

while True:
    city = input(prompt)

    if city == 'quit':
        break
    else:
        print("I'd love to go to " + city.title() + "!")

2.5 在循环中使用continue

返回至循环开头,并根据条件测试结果决定是否继续执行循环。只结束单次循环

e.g. 只打印10以内的奇数。

(理解:if 语句检查current_number 与2的求模运算的结果,若结果为0,执行 continue 语句,忽略余下的代码并返回到循环的开头;若当前的数字不能被2整除,就执行循环中余下的代码。)

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

2.6 避免无限循环

  • 当程序陷入无限循环时,“control +C” 结束程序;
  • 务必对每个 while 循环进行测试,确保其如预期那样结束

练习

电影票:有家电影院根据观众的年龄收取不同票价:不到3岁的观众免费;3~12岁观众为10美元;超过12岁的观众为15美元。编写一个while 循环,在其中询问用户的年龄,并指出其票价。

  • 在while 循环中使用条件测试来结束循环
  • 使用变量active来控制循环结束的时机
  • 使用break语句在用户输入'quit'时退出循环
prompt = "How old are you? Please input your age: "
active = True
while active:
    age = input(prompt)
    if age =='quit':
        break
    else:
        age = int(age)  #!!!<class 'str'> --> <class 'int'>
        if age < 3:
            print("Free.")
        elif age <= 12:
            print("10$.")
        else:
            print("15$.")

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

  • for循环时遍历列表的有效方式,但在for循环中不应修改列表(否则将导致python难以跟踪其中的元素)
  • 使用while循环在遍历列表的同时修改列表,将while循环与列表、字典结合使用,可收集、存储并组织大量输入,供以后查看

3.1 在列表之间移动元素

空列表作为判断条件时,为False。

# 首先,创建一个待验证用户列表
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())

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

e.g 假设有一个宠物列表,其中包含多个值为'cat'的元素,删除所有这些元素。

(remove() 只删除第一个匹配的元素)

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

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

print(pets)

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

e.g 使用while循环提示用户输入任意数量的信息,并将用户的名字和回答存储在一个字典中。

responses = {}

# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
    # 提示输入被调查者的名字和回答
    name = input("\nWhat's your name? ")
    response = input("\nWhich mountain would you like to climb someday? ")

    # 将答案存储在字典中
    responses[name] = response

    #查看是否有人参与调查
    repeat = input("Would you like to let another person repond?(yes/no)")
    if repeat == 'no':
        polling_active = False

# 调查结果,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name.title() + " would like to climb " + response + ".")