Python编程:从入门到实践——第7章、用户输入和while 循环(附课后题)

函数input()

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

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

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

int 与input()的使用

#int() 获取输入
age = input("How old are you?")
age = int(age)#将输入age转为int类型
if age >= 18:#此处需要int类型对比
    print("\n已成年")
else:
    print("\n未成年")

#奇数\偶数判断
number = input("输入一个数字,判断奇数还是偶数:")
number = int(number)
if number % 2 == 0:
    print("\n您输入的数字“" + str(number) + "”" + "是偶数。")
else:
    print("\n您输入的数字“" + str(number) + "”" + "是奇数。")

while循环

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

prompt = "\n告诉我你想重复的一句话:"
prompt += "\n输入 '退出',程序结束."
message = ""
while message != '退出':
    message = input(prompt)
    if message != '退出':
        print(message)

使用标志,简化循环语句中的条件判断

prompt = "\n告诉我你想重复的一句话:"
prompt += "\n输入 '退出',程序结束."
active = True
while active:
    message = input(prompt)
    if message == '退出':
        active = False
    else:
        print(message)

break退出循环

#while True打头的循环,会不断执行,直到遇到breakbreak可用在遍历列表或字典
prompt = "\n请输入你喜欢居住的城市名字:"
prompt += "\n输入 '退出',程序结束."
while True:
    city = input(prompt)
    if city == '退出':
        break
    else:
        print("你喜欢居住在" + city + "!")

循环中使用continue,返回循环开头,根据条件判断是否继续执行循环

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

避免无限循环

#循环中未处理x,导致值始终为1,循环无法停止
x = 1
while x <= 5:
    print(x)

while 循环来处理列表和字典

列表间移动元素(假定一个列表,包含新注册但未验证用户,需验证后,移动到已验证列表)

unconfirmed_users = ['张三','李四','王五']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("验证用户:" + current_user.title())
    confirmed_users.append(current_user)
print("\n用户已全部验证完毕,列表如下:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

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

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

使用用户输入来填充字典

可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来:

responses = {}
#设置一个标志,指出调查是否继续
polling_active = True

while polling_active:
    #提示输入被调查者的名字和回答
    name = input("\n你的姓名?")
    response = input("请问你哪天想去那座城市?")

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

    #看看是否还有人要参与调查
    repeat = input("是否还有人想要参与问卷调查?(yes/ no)")
    if repeat == 'no':
        polling_active = False

#调查结束,显示结果
print("\n----调查 结束 ----")
for name,response in responses.items():
    print(name + "想去" + response + "。")

练习题

#7-1
#汽车租赁 :编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如“Let me see if I can find you a Subaru”。
car = input("您需要租赁什么样的汽车:")
print("\n请稍等,让我看看能否找到你需要的" + car + "汽车。")
#7-2
#餐馆订位 :编写一个程序,询问用户有多少人用餐。如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌。
pop = input("请问几位人员用餐:")
pop = int(pop)
if pop > 8:
    print("您好,你预定的人数较多,没有空桌。")
else:
    print("您好,有空桌提供用餐。")
#7-3
#10的整数倍 :让用户输入一个数字,并指出这个数字是否是10的整数倍。
number = input("请输入一个数字:")
number = int(number)
if number % 10 == 0:
    print(str(number) + "是10的倍数")
else:
    print(str(number) + "不是10的倍数")
#7-4
#比萨配料 :编写一个循环,提示用户输入一系列的比萨配料,并在用户输入'quit' 时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨
#中添加这种配料。
piza = ("请您告诉我需要给披萨添加什么配料或输入'退出'结束:")
while True:
    pizas = input(piza)
    if pizas == '退出':
        break
    else:
        print("我们在披萨中添加了您需要的:" + pizas + "作料。")
#7-5
#电影票 :有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众为10美元;超过12岁的观众为15美元。请编写一个循环,在其中询问用
#户的年龄,并指出其票价。
age = ("请问你的年龄多大?")

while True:
    inputage  = input(age)
    if '退出' in inputage:
        print("程序结束")
        break
    elif int(inputage) < 3:
        print("您的票价免费!")
    elif 3 <= int(inputage) <= 12:
        print("您的票价10美元")
    elif int(inputage) > 12:
        print("您的票价15美元") 
#7-6
#三个出口 :以另一种方式完成练习7-4或练习7-5,在程序中采取如下所有做法。
#在while 循环中使用条件测试来结束循环。
#使用变量active 来控制循环结束的时机。
#使用break 语句在用户输入'quit' 时退出循环。
#7-4(2)
piza = ("请您告诉我需要给披萨添加什么配料或输入'退出'结束:")
active = True
while active:
    pizas = input(piza)
    if pizas == '退出':
        print("已退出添加配料")
        active = False
    else:
        print("我们已在披萨里添加" + pizas + "配料!")

#7-5(2)
moveage = ("请告输入您的年龄")
moveage += ("\n输入'退出',结束订票\n:")
active = True
while active:
    ticket = input(moveage)
    if ticket == '退出':
        print("退出订票\n")
        break
    elif int(ticket) < 3:
        print("票价免费")
    elif 3 <= int(ticket) <= 12:
        print("票价10美元")
    elif int(ticket) > 12:
        print("票价15美元")
    print("\n")
print("感谢您的购票,欢迎再来!")
#7-8 熟食店 :创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches 的空列表。遍历列
#表sandwich_orders ,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表finished_sandwiches 。所有三明
#治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['火腿三明治','蔬菜三明治','水果三明治']
finished_sandwiches = []
while sandwich_orders:
        sandwich  = sandwich_orders.pop()
        finished_sandwiches.append(sandwich)
        print("我做了你要的 " + sandwich + '。\n')

for finished_sandwiche in finished_sandwiches:
    print(finished_sandwiche)
#7-9 五香烟熏牛肉(pastrami)卖完了 :使用为完成练习7-8而创建的列表sandwich_orders ,并确保'pastrami' 在其中至少出现了三次。在程序开头附近添加
#这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while 循环将列表sandwich_orders 中的'pastrami' 都删除。确认最终的列
#表finished_sandwiches 中不包含'pastrami' 。
sandwich_orders = ['火腿三明治','pastrami','蔬菜三明治','pastrami','pastrami','水果三明治']
print('熟食店的五香烟熏牛肉买完了!')
active = True
while active:
    if 'pastrami' in sandwich_orders:
        sandwich_orders.remove('pastrami')
    else:
        active = False
print(sandwich_orders)
#7-10 梦想的度假胜地 :编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查
#结果的代码块。
visitdict = {}
active = True
print("你有没有特别想要去度假的地方?,请完成下面的问卷调查。")
while active:
    name = input("\n请输入您的姓名:")
    visit = input("\n请输入您想去旅游的地方:")
    visitdict[name] = visit
    repeat = input("\n是否还有人要参与问卷调查?(yes/ no)")
    if repeat == 'no':
        active = False
print("\n---结束调查---")
for name,visit in visitdict.items():
    print(name + "想去" + visit + "。")

猜你喜欢

转载自blog.csdn.net/github_35707894/article/details/80569468