总结
本章学习了:
如何使用input()来让用户提供信息
如何处理文本和数字输入
一般来说,input获取的是字符串,可使用int()将其转化成数字
如何使用while循环让程序按用户的要求不断运行
while循环不断运行,直到指定的条件不满足为止
多种控制while循环流程的方式:
-
设置活动标志(在要求很多条件都满足才能继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。你可以让程序在标志为True时运行,并在任何事件导致标志变为False时停止。)
-
使用break语句以及使用continue语句
如何使用while循环在列表之间移动元素
如何从列表中删除所有包含特定值的元素
如何结合使用while循环和字典
动手试一试
7-1汽车租赁
# 7-1汽车租赁
def func01():car_names = input("Let me see fi I can find you a Subaru: ")
7-2餐馆订位
# 7-2参观订位
def func02():number = input("请问有多少人用餐? ")number = int(number)if number > 8:print("对不起没有空桌了.")else:print("现在还有空桌.")
7-3 10的整数倍
# 7-3 10的整数倍
def func03():number = input("请输入一个数字: ")number = int(number)if number % 10 == 0:print("它是10的整数倍")else:print("它不是10的整数倍")
7-4比萨配料
# 7-4比萨配料
def func04():message = "\n请输入一系列比萨配料:"message += "\nEnter 'quit' to end the program."burden = ""while burden != 'quit':burden = input(message)if burden != 'quit':print("我们会在比萨中添加这种配料:%s" % burden)else:print("结束.")
7-5电影票
# 7-5电影票
def func05():promopt = '\n请问您的年龄是: 'promopt += "\nEnter 'quit' to end the program: "while True:age = input(promopt)if age == 'quit':print("程序结束")breakage = int(age)if age < 3:print("你的票价是免费的.")elif age <= 12:print("你的票价是10美元")else:print("你的票价为15元")
当我试图输入别的字符串时,程序报错,我暂时还不知道怎么改。
请问您的年龄是:
Enter 'quit' to end the program: er
Traceback (most recent call last):
File "D:/E_workspace/pycharm_work/first/capter07.py", line 60, in <module>
func05()
File "D:/E_workspace/pycharm_work/first/capter07.py", line 51, in func05
age = int(age)
ValueError: invalid literal for int() with base 10: 'er'
Process finished with exit code 1
7-6三个出口 (这里改了一下,用了标志)
# 7-6电影票
def func06():promopt = '\n请问您的年龄是: 'promopt += "\nEnter 'quit' to end the program: "active = Truewhile active:age = input(promopt)if age == 'quit':print("程序结束")active = Falseelse:age = int(age)if age < 3:print("你的票价是免费的.")elif age <= 12:print("你的票价是10美元")else:print("你的票价为15元")
7-7无限循环
# 7-7无限循环
def func07():n = 1while n < 5:print(n)