【Python学习】六、用户输入与while循环

6.1 input()工作原理

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

name = input("Please enter your name:")
print(name.title() + ', good morning!')

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

函数int() ,它让Python将输入视为数值。函 数int() 将数字的字符串表示转换为数值表示

age = input('How old are you?')
age = int(age)
if age >= 18:
    print("You are able to drink!")

6.1.2 求模运算符 

求模运算符 (%)是一个很有用的工具,它将两个数相除并返回余数

number = input("Please enter a number:")
number = int(number)
if number % 2 == 0:
    print(str(number) + "is even.")
else:
    print(str(number) + ' is odd.')

6.2 while循环

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

6.2.1 简单while循环

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

6.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)
    print(message)

这个程序很好,唯一美中不足的是,它将单词'quit' 也作为一条消息 打印了出来。为修复这种问题,只需使用一个简单的if测试 

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)

 6.2.3 使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志 ,充当了程序的交通信号灯。

你可让程序在标志为True时继续运行,并在任何事件导 致标志的值为False时让程序停止运行。

这样,在while 语句中就只需检查一个条件——标志的当前值是否为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 = True
        print(message)
    else:
        active = False

我们将变量active 设置成了True,让程序最初处于活动状态。

这样做简化了while 语句,因为不需要在其中做任何比较——相关的逻辑由程序的其他部分处理。只要变量active为True ,循环就将继续运行。

6.2.4 使用break退出循环

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。

prompt = '\nPlease enter the cities you have visited:'
prompt += '\n Please key in "quit" when you finish.'

while True:
    cities = input(prompt)
    if cities == 'quit':
        break
    else:
        print(cities.title())

6.2.5 在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句.

它不像break 语句那样不再执行余下的代码并退出整个循环。

# 只打印1-10之间的奇数
number = 0

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

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

要记录大量的用户和信息,需要在while 循环中使用列表和字典。

要在遍历列表的同时对其进行修改,可使用while循环。

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

6.3.1 在列表之间移动元素

# 将一个列表中的数据移动到另一个列表中
alternative_cities = ['Beijing', 'Jinan', 'Nanking']
visited_cities = []
while alternative_cities:
    current_cities = alternative_cities.pop()
    print("I am visiting " + current_cities + ".")
    visited_cities.append(current_cities)

print("I have visited these cities:")
for city in visited_cities:
    print(city)

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

在第2章中,我们使用函数remove() 来删除列表中的特定值,这之所以可行,是因为要删除的值在列表中只出现了一次。如果要删除列表中所 有包含特定值的元素,该怎么办呢?

cities = ['beijing', 'beijing', 'nanking', 'suzhou', 'hongkong', 'taipei']
while 'beijing' in cities:
    cities.remove('beijing')
for city in cities:
    print(city)

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

可使用while循环提示用户输入任意数量的信息。

cities = {}
active = True
while active:
    name = input("\nPlease key in your name:")
    city = input('\nPlease key in your favourite city:')
    cities[name] = city
    ask = input('"Would you like to let another person respond? (Y/N)')
    if ask == 'N':
        active = False


for key, value in cities.items():
    print(key.title() + "'s favourite city is "+ value.title() +".")

6.4 练习

6-1 汽车租赁 :编写一个程序,询问用户要租赁什么样的汽车,并 打印一条消息,如“Let me see if I can find you a Subaru”。

# 6-1
car = input('Which car do you want?')
print('Let me see if I can find you a ' + car + '.')

6-2 餐馆订位 :编写一个程序,询问用户有多少人用餐。如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌。 

# 6-2
number = input('How many people will come to eat?')
if int(number) > 8:
    print("Sorry, we don't have spare desk.")
else:
    print("Welcome!")

6-3 10的整数倍 :让用户输入一个数字,并指出这个数字是否是10 的整数倍。

number = input('Please key in a number:')
if int(number) % 10 == 0:
    print(number + '是10的整数倍.')
else:
    print(number + '不是10的整数倍.')

 

 

6-4 比萨配料 :编写一个循环,提示用户输入一系列的比萨配料, 并在用户输入'quit' 时结束循环。每当用户输入一种配料后,都 打印一条消息,说我们会在比萨中添加这种配料。

# 6-4
prompt = '请输入你想加入的披萨料:\n'
prompt += '(如果退出请按quit!)'
active = True
while active:
    moppings = input(prompt)
    if moppings == 'quit':
        active = False
    else:
        print('我们会加入' + moppings + '.')

 

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

# 6-5
prompt = '请输入年龄:\n'
prompt += '(如果退出请按quit!)'
active = True
while active:
    age = input(prompt)
    if age == 'quit':
        break
    else:
        age = int(age)
        if age < 3:
            print("免费!")
        elif age < 12:
            print('您的票价为10美元!')
        else:
            print('您的票价为15美元!')

 

6-8 熟食店 :创建一个名为sandwich_orders 的列表,在其中包 含各种三明治的名字;

再创建一个名为finished_sandwiches 的 空列表。遍历列表sandwich_orders ,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表finished_sandwiches 。所有三明治都制作好后,打印一条消息,将这些三明治列出来。

# 6-8
sandwich_orders = ['apple sandwich', 'peach sandwich', 'watermelon sandwich']
finished_sandwiches = []
while sandwich_orders:
    making_sandwich = sandwich_orders.pop()
    print("I made your " + making_sandwich + '.')
    finished_sandwiches.append(making_sandwich)

for sandwich in finished_sandwiches:
    print(sandwich)

 

6-9 五香烟熏牛肉(pastrami)卖完了 :使用为完成练习6-8而创建的列表sandwich_orders ,并确保'pastrami' 在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while 循环将列表sandwich_orders 中的'pastrami' 都删除。确认最终的列表finished_sandwiches 中不包含'pastrami' 。

 

# 6-9
sandwich_orders = ['apple sandwich', 'pastrami sandwich',  'peach sandwich', 'pastrami sandwich',
                   'watermelon sandwich', 'pastrami sandwich']
print("熟食店的五香烟熏牛肉卖完了!")
while 'pastrami sandwich' in sandwich_orders:
    sandwich_orders.remove('pastrami sandwich')
finished_sandwiches = []
while sandwich_orders:
    making_sandwich = sandwich_orders.pop()
    print("I made your " + making_sandwich + '.')
    finished_sandwiches.append(making_sandwich)

for sandwich in finished_sandwiches:
    print(sandwich)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值