小菜鸟的python学习之路(6)

学习阶梯

《Python编程:从入门到实践》

  • 第一部分:基础知识
第7章 用户输入和while循环
  1. 函数input()的工作原理

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

parrot.py

message=input("Tell me something, and I will repeat it back to you: ")
print(message)
  • 编写清晰的程序

greeter.py

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

创建多行字符串:
第1行将消息的前半部分存储在变量prompt中;
在第2行中,运算符+=在存储在prompt中的字符串末尾附加一个字符串


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

使用函数input()时,Python将用户输入解读为字符串

将输入用于数值比较时,Python会引发错误,因为它无法将字符串和整数进行比较:不能将存储在age中的字符串’21’与数值18进行比较

age = input("How old are you? ")
age = int(age)
print(age >= 18)

rollercoaster.py

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

  • 求模运算符

parrot.py

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

#判断一个数是奇数还是偶数
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.")

练习

#7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如“Let me see if I can find you a Subaru”。
car= input("\nWhat kind of car would you like to rent? ")
print("\nLet me see if I can find you a "+car.title())
#7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过 8 人,就打印一条消息,指出没有空桌;否则指出有空桌。
people= input("\nHow many people are eating?")
people=int(people)
if people>8:
    print("\nSorry, there is no table available.")
else:
    print("\nThere are some available tables, and you can reserve.")
#7-3 10的整数倍:让用户输入一个数字,并指出这个数字是否是 10 的整数倍。
number=input("\nPlease enter a number: ")
number=int(number)
if number%10==0:
    print("\nIt's a multiple of 10.")
else:
    print("\nIt's not a multiple of 10.")
  1. while循环简介

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

counting.py

  • 使用while循环
current_number=1
while current_number<=5:
    print(current_number)
    current_number+=1

  • 让用户选择何时退出
prompt="\nTell me something, and I will repeat it back to you: "
prompt+="\nEnter 'quit' to end the program.\n"
message=" "
while message !='quit':
    message=input(prompt)
    if message!='quit':
        print(message)

  • 使用标志

可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,可让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。

prompt = "\nTell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program.\n"
active=True
while active:
    message=input(prompt)
    if message=='quit':
        active=False
    else:
        print(message)

  • 使用break退出循环

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。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
    else:
        print("I'd love to go to "+city.title()+"!")

  • 在循环中使用continue

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

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

  • 避免无限循环
x=1
while x<=5:
    print(x)
    x+=1

如果程序陷入无限循环,可按Ctrl + C,也可关闭显示程序输出的终端窗口。

要避免编写无限循环,务必对每个while循环进行测试,确保它按预期那样结束。

如果希望程序在用户输入特定值时结束,可运行程序并输入这样的值;如果在这种情况下程序没有结束,请检查程序处理这个值的方式,确认程序至少有一个这样的地方能让循环条件为False或让break语句得以执行。

练习

#7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit'时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。
prompt="\nPlease enter the ingredients you want to add: "
prompt+="\n(Enter 'quit' when you are finished.)"
message=" "
while message!='quit':
    message=input(prompt)
    if message!='quit':
        print(message+" will be add to your pizza!")
#7-5 电影票:有家电影院根据观众的年龄收取不同的票价:不到 3 岁的观众免费;3~12 岁的观众为 10 美元;超过 12 岁的观众为 15 美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。
prompt="\nPlease enter the age of the viewer: "
prompt="\n(Enter 'quit' when you are finished.)"
age=" "
active=True
while active:
    age=input(prompt)
    if age=='quit':
        active=False
        break
    age=int(age)
    if age<3:
        print("\nHello, you're less than 3 years old. The ticket is free.")
    elif age<=12:
        print("\nHello, you are between 3 and 12 years old. The ticket is 10 dollars.")
    else:
        print("\nHello, you are over 12 years old. The ticket is 15 dollars.")
#7-6 三个出口:以另一种方式完成练习 7-4 或练习 7-5,在程序中采取如下所有做法。
## 在 while 循环中使用条件测试来结束循环。
## 使用变量 active 来控制循环结束的时机。
## 使用 break 语句在用户输入'quit'时退出循环。
prompt = "\nPlease enter the age of the viewer: "
prompt = "\n(Enter 'quit' when you are finished.)"
age = " "
active = True
while active:
    age = input(prompt)
    if age == 'quit':
        active = False
        break
    age = int(age)
    if age < 3:
        print("\nHello, you're less than 3 years old. The ticket is free.")
    elif age <= 12:
        print(
            "\nHello, you are between 3 and 12 years old. The ticket is 10 dollars."
        )
    else:
        print("\nHello, you are over 12 years old. The ticket is 15 dollars.")
#7-7 无限循环:编写一个没完没了的循环,并运行它(要结束该循环,可按 Ctrl +C,也可关闭显示输出的窗口)
x=0
while x<=5:
    print(x)
    #x+=1
  1. 使用while循环来处理列表和字典

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

for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。

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

confirmed_users.py

  • 在列表之间移动元素
#首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
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())

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

使用函数remove()来删除列表中的特定值

pets=['dog', 'cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

  • 使用用户输入来填充字典
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+".")

练习

#7-8 熟食店:创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches 的空列表。遍历列表 sandwich_orders,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich,并将其移到列表finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['pepperoni', 'chicago-sytle', 'joes', 'greek']
finished_sandwiches=[]
while sandwich_orders:
    finished_sandwich=sandwich_orders.pop()
    print("I made your "+finished_sandwich+"sandwich.")
    finished_sandwiches.append(finished_sandwich)
print("The finished sandwiches are as follows:")
for finished_sandwich in finished_sandwiches:
    print("\t"+finished_sandwich)
#7-9 五香烟熏牛肉(pastrami)卖完了:使用为完成练习 7-8 而创建的列表sandwich_orders,并确保'pastrami'在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个 while 循环将列表 sandwich_orders 中的'pastrami'都删除。确认最终的列表 finished_sandwiches 中不包含'pastrami'。
sandwich_orders = ['pepperoni', 'pastrami','chicago-sytle','pastrami', 'joes', 'greek','pastrami',]
print("The Deli is out of pastrami!")
while 'pastrami' in sandwich_orders:
    sandwich_orders.remove('pastrami')
print("The final list is :")
for sandwich_order in sandwich_orders:
    print("\t"+sandwich_order)
#7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查结果的代码块。
prompt ="\nIf you could visit one place in the world, where would you go? "
prompt+="\n(Enter 'quit' when you are finished.)\n"
message=" "
while message!='quit':
    message=input(prompt)
    if message!='quit':
        print(message)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值