【毕设记录日记】Python基础内容笔记整理5:用户输入、while循环

【毕设记录日记】Python基础内容笔记整理5:用户输入、while循环,第1张

写的越来越多了,不放前篇了, 都在Python学习的文件夹里,这个部分马上要结束了,会写一个统一的目录篇。


1 函数input()

(1)函数input()让程序暂停运行,等待用户输入文本,并在用户按回车键后继续运行。


(2)函数input()接受一个参数:要向用户显示的提示或说明,让用户知道如何做。


(3)当提示超过一行时,可将提示存储在一个变量中,再将该变量传递给input()。


prompt = "Tell me your name"
prompt += "\nPlease enter:"

name=input(prompt)
print("\n"+name)

运算符+=在存储在prompt中的字符串末尾附加一个字符串。


2 函数int()

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


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


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

if age<3:
    print("Cute baby!")
else:
    print("Programming should start with children!")

将输入变为数值表示后可以用作后续与其他数值进行比较,执行所需的相应 *** 作。


3 求模运算符%

(1)求模运算符%将两数相处并返回余数。


(2)当一个数可以被另一个数整除,余数为0,因此求模运算符将返回0。


4 while循环 4.1 while循环与for循环

for循环:用于针对集合中每个元素都使用一个代码块

while循环:不断运行,直到指定条件不满足为止

4.2 让用户选择何时退出

(1)使用while循环可以让程序在用户愿意时不断运行,若在程序中设置退出值,只要用户输入的不是这个值,程序就接着运行。


(2)如果不需要程序在结尾输出退出值可以使用if语句,

if message != 'quit':
    print(message)

程序在显示消息前做简单的检查,仅在消息不是退出值时才打印它。


4.3 使用标志

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


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


(3)这样做只需要在while中检查标志此时是否为True即可决定是否运行如下循环,并且将所有测试(是否发生了应将标志设置为False的事件)都放在其他地方,从而让程序变得更为整洁。


(4)可以给标志指定任何名称

4.4 使用break退出循环

(1)使用break语句可以不管条件测试的结果如何,立即退出while循环。


(2)break语句用于控制程序流程,可以使用它来控制哪些代码行将执行,哪些代码行不执行。


(3)在任何Python循环中都可以使用break语句。


例如,使用break语句来退出遍历列表或字典的for循环。


4.5 在循环中使用continue

(1)使用break语句将会直接使程序退出整个循环而不执行余下代码,使用continue语句会跳回循环开头,进入下一个循环。


4.5  避免无限循环

(1)如果程序进入无限循环,可以按Ctrl+C停止运行,也可以直接关闭程序输出的终端窗口。


(2)避免无限循环,需要对每个while循环进行测试,确保按预期结束。


如果在测试过程中特定值没有使循环结束,则需要检查程序。


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

for循环可以用来遍历列表,但如果需要遍历并对列表进行一些 *** 作,例如修改,则需要使用while循环。


5.1 列表之间移动元素

(1)使用方法pop()从原本的列表中d出元素,再使用方法append()添加进新列表中。


(2)具体抽象结构见思维导图。


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

(1)使用函数remove()可以删除列表中的特定值,如果列表中有多个需要删除的特定值,可以在循环中使用函数remove()。


(2)函数remove()要求输入需要删除的元素。


(3)具体抽象结构见思维导图。


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

(1)具体抽象结构见思维导图。


6 课后题

具体题目都在注释中打印出来了。


#ex7-1 car_rental
#编写一个程序,询问用户需要租赁什么样的汽车
#打印一条消息,如"Let me see if I can find you a Subaru"
car_rental=input("What brand of vehicle do you want to rent? ")

print("Let me see if I can find you a "+car_rental+".\n")

#ex7-2 restaurant_positioning
#编写一个程序,询问用户有多少人用餐
#若超过8人,则打印一条消息指出没有空桌;否则指出有空桌
number_of_diners=input("Hello, how many customers need dinner? ")
number_of_diners=int(number_of_diners)

if number_of_diners > 8:
    print("I'm sorry that there are no available tables for dinner at present.\n")
else:
    print("There are available tables for dining at present.\n")

#ex7-3 integral_multiple_of_10
#让用户输入一个数字,并指出这个数字是否是10的整数倍
integral_multiple_of_10=input("Please enter a number and I will help you verify whether it is an integer multiple of 10. ")
integral_multiple_of_10=int(integral_multiple_of_10)

if integral_multiple_of_10%10==0:
    print("This number is an integer multiple of 10.\n")
else:
    print("This number isn't an integer multiple of 10.\n")

#ex7-4 pizza
#编写一个循环,提示用户输入一系列披萨配料,并在用户输入'quit'时结束循环
#每当用户输入一种配料后,都打印一条消息,说明我们会在pizza中添加这种配料
pizza_ingredients = "Please enter the ingredients what you want to add to the pizza."
pizza_ingredients += "\nEnter: "

while True:
    ingredients = input(pizza_ingredients)

    if ingredients == 'quit':
        break
    else:
        print("OK, we'll add this ingredient that named "+ingredients.title()+" for you.")
print("\n")

#ex7-5 ticket_price
#电影院根据观众年龄收取不同票价:小于3岁的观众免费;3~12岁的观众10美元;超过12岁的观众为15美元
#编写一个循环,询问用户年龄,并指出票价
prompt = "We will charge different fares according to your age. The rules are as follows:"
prompt += "\nAudiences younger than 3 years old are free."
prompt += "\nThe audience aged 3~12 is charged $10."
prompt += "\nThe audience over the age of 12 is charged $15."
prompt += "\nPlease enter your age:"

while True:
    age = input(prompt)
    age = int(age)

    if age == 0:
        break
    else:
        if age < 3:
            print("You are a free audience!")
        elif age < 12:
            print("You need to pay a fare of .")
        else:
            print("You need to pay a fare of .")

print("\n")

#ex7-7 无限循环测试
#编写一个无限循环试运行
#按Ctrl+C结束循环关闭窗口
#number = 1

#while number != 0:
#    print(number)

#ex7-8 sandwich_orders
#创建名为sandwich_orders的列表
#其中包含各种三明治的名称
#再创建一个名为finished_sandwich的空列表
#遍历sandwich_orders,对于每种三明治都打印一条消息,如:I made your tuna sandwich,并将其移到列表finished_sandwiches
#所有三明治制作好后,打印一条消息,将这些三明治列出来
sandwich_orders=['tuna sandwich','ham sandwich']
finished_sandwich=[]

while sandwich_orders:
    sandwich_order = sandwich_orders.pop()
    
    print("I made your "+sandwich_order+".")
    finished_sandwich.append(sandwich_order)

print("\nThe finished sandwiches are:")
for finished_sandwich_element in finished_sandwich:
    print(finished_sandwich_element)
print("\n")

#ex7-9 pastrami
#使用ex7-8创建的列表sandwich_orders,并确保'pastrami'在其中至少出现了三次
#在程序开头附近添加代码:指出熟食店的五香烟熏牛肉卖完了
#使用一个while循环将列表sandwich_orders中的'pastrami'都删除
#确认最终的列表finished_sandwiches中不包含'pastrami'
sandwich_orders=['pastrami sandwich','tuna sandwich','pastrami sandwich','ham sandwich','pastrami sandwich']
print("We're out of pastrami in the deli.")

while 'pastrami sandwich' in sandwich_orders:
    sandwich_orders.remove('pastrami sandwich')

print(sandwich_orders)
print("\n")

#ex7-10 dream_place
#编写一个程序,调查用户梦想的度假胜地
#使用类似于"If you could visit one place in the world,where would you go?"的提示
#并编写一个打印调查结果的代码块
responses={}

polling_active=True

while polling_active:
    name = input("What's your name? ")
    dream_place = input("If you could visit one place in the world,where would you go? ")

    responses[name] = dream_place

    repeat = input("Would you like to let another person respond?(yes/no) ")
    if repeat == 'no':
        polling_active = False
    else:
        print("\n")

print("\n---Poll Results---")
for name,dream_place in responses.items():
    print(name.title()+" would like go to "+dream_place.title()+".")

print("\n")

 参考书籍:Python编程从入门到实践(书籍) - 知乎 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/567975.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存