(一)循环

(1)循环的介绍

循环语句用于多次、重复性地执行一组语句,其控制结构图如下:
第二课:循环与字符串 - 图1

(2)while循环

1) while循环语句的一般形式

  1. while condition:
  2. statement

下面的while循环实现了计算从1到100的和

  1. sum = 0
  2. i = 0
  3. while i < 100:
  4. i += 1
  5. sum += i
  6. print("从1到{:d}的和为{:d}".format(i, sum))

运行结果为:

  1. 1100的和为5050

2)无限while循环

无限循环,意味着while语句的condition永远为true,循环不会结束
例如:

  1. while 1 == 1 :
  2. statement
  3. i = 1
  4. while i > 0 :
  5. statement

通常,这种循环用于处理客户端的实时请求,例如:

  1. #在屏幕显示菜单,当用户做出选择后输出用户的输出信息,然后回车后返回菜单继续
  2. while 1==1:
  3. print("{:^200} \n".format("Menu List"))
  4. print("{:<200}\n".format("我们向您提供以下各种口味的奶茶:"))
  5. print("{:<200}\n".format("1.原味冰奶茶,每杯3元"))
  6. print("{:<200}\n".format("2.香蕉冰奶茶,每杯5元"))
  7. print("{:<200}\n".format("3.草莓冰奶茶,每杯5元"))
  8. print("{:<200}\n".format("4.蒟蒻冰奶茶,每杯7元"))
  9. print("{:<200}\n".format("5.珍珠冰奶茶,每杯7元"))
  10. choice=input("请输入数字1-5来选择对应的你喜欢的口味(1-5):")
  11. print("你选择了%s号奶茶" % choice)
  12. input("按任意键回车后返回菜单")

3)while…else语句

while…else用于实现循环的分支控制,即:当条件成立,为True的时候,执行while循环体中的语句,反之,执行else循环体中的语句
其形式如下:

  1. while condition :
  2. statement1
  3. else :
  4. statement2

例如:

  1. sum = 0
  2. i = 0
  3. while i<100 :
  4. i += 1
  5. sum += i
  6. else:
  7. print("Calculation finnished, the result is {:d}".format(sum))

运行结果为:

  1. Calculation finnished, the result is 5050

(3)for循环

for语句在Python当中非常重要,在遍历序列项目的应用中非常广泛
其一般形式为:

  1. for <variable> in <sequence>:
  2. <statements>
  3. else:
  4. <statements>

使用for语句遍历元组

  1. tu1 = ("do","what","done","be")
  2. i = 0
  3. for item in tu1 :
  4. i += 1
  5. print("ITEM %d is: %s" % (i,item))

运行结果为:

  1. ITEM 1 is: do
  2. ITEM 2 is: what
  3. ITEM 3 is: done
  4. ITEM 4 is: be

使用for语句遍历列表

  1. list1 = ["To","be","or","not","to","be,","that's","a","question!"]
  2. for item in list1:
  3. print("{} ".format(item),end="")

运行结果为:

  1. To be or not to be, that's a question!

使用for语句遍历字典

  1. dict1 = {"start_point":"116,89","end_point":"89","distance":"110.98","direction":"Northeast"}
  2. for key in dict1:
  3. print(dict1[key])

运行结果为:

  1. 116,89
  2. 89
  3. 110.98
  4. Northeast

(4)range函数

range函数往往和for语句配合使用,用于对数字序列的遍历
例如:

  1. #类似于c语言中的for(i=0;i<=9;i++)
  2. for i in range(10) :
  3. print("i=%d" % i )

运行结果为:

  1. i=0
  2. i=1
  3. i=2
  4. i=3
  5. i=4
  6. i=5
  7. i=6
  8. i=7
  9. i=8
  10. i=9

range函数也可以指定生成数字序列的初值和终值,以及步长
例如:

  1. #指定初值和终值(初值包含,终值不包含,步长为1)
  2. for i in range(5,10) :
  3. print("i=%d" % i )
  4. print("-----------------------")
  5. #指定初值,终值,步长为1
  6. for i in range(3,11,2):
  7. print("i=%d" % i)
  8. print("########################")
  9. #初值、终值和步长都可以为负数
  10. for i in range(11, 2, -3):
  11. print("i=%d" % i)

结果为:

  1. i=5
  2. i=6
  3. i=7
  4. i=8
  5. i=9
  6. -----------------------
  7. i=3
  8. i=5
  9. i=7
  10. i=9
  11. ########################
  12. i=11
  13. i=8
  14. i=5

上课例题:打印一个图案

  1. for i in range(0,4):
  2. print(' '*i,end="")
  3. print("*"*(7-2*i))
  4. for i in range(2,-1,-1):
  5. print(' '*i,end="")
  6. print("*"*(7-2*i))

运行可得:

  1. *******
  2. *****
  3. ***
  4. *
  5. ***
  6. *****
  7. *******

(5)len()函数

len()函数用于返回一个序列的长度,例如元组、列表或者字典等
例如:

  1. tu1 = ("do","what","done","be")
  2. list1 = ["To","be","or","not","to","be,","that's","a","question!"]
  3. dict1 = {"start_point":"116,89","end_point":"89","distance":"110.98","direction":"Northeast"}
  4. #打印元组,列表和字典的长度
  5. print("%d,%d,%d" % (len(tu1), len(list1), len(dict1)))

结果为:

  1. 4,9,4

(6)range和len结合以遍历一个序列

例如:

  1. print("----------list---------")
  2. list1 = ["To","be","or","not","to","be,","that's","a","question!"]
  3. #利用range配合len函数来生成列表的索引序列,并逐一打印索引下标和列表各个元素
  4. for i in range(len(list1)) :
  5. print("i=%d,item=%s" % (i,list1[i]))
  6. print("----------tuple----------")
  7. tu1 = ("do","what","done","be")
  8. #利用range配合len函数来生成元组的索引序列,并逐一打印索引下标和元组
  9. for i in range(len(tu1)):
  10. print("i=%d,item=%s" % (i,tu1[i]))
  1. ----------list---------
  2. i=0,item=To
  3. i=1,item=be
  4. i=2,item=or
  5. i=3,item=not
  6. i=4,item=to
  7. i=5,item=be,
  8. i=6,item=that's
  9. i=7,item=a
  10. i=8,item=question!
  11. ----------tuple---------
  12. i=0,item=do
  13. i=1,item=what
  14. i=2,item=done
  15. i=3,item=be

(7) break语句

break语句用于跳出for或者while循环体。当使用break的时候,将从对应的循环体跳出
例如:

  1. s1="No pain"
  2. s2="No gain"
  3. #对s1,s2字符串进行合并,然后取出逐个字母
  4. for letter in s1+" "+s2 :
  5. print(letter, end="")
  6. #判断,如果当前字母为o,则退出循环
  7. if letter == 'o':
  8. break

结果为

  1. No

如果是多重循环,则只退出break语句所在的循环体,并不退出外重循环,例如

  1. # i负责直角三角形个数,j负责直角三角形的行数。由于在内层循环中使用了break,则只打印了五行,但是break不会导致退出外层循环,因而直角三角形个数仍然是3个。
  2. for i in range(0,3):
  3. print("-"*(2*i),end="")
  4. for j in range(0,10):
  5. print("*"*j)
  6. if j==5 :
  7. break

运行结果为

  1. *
  2. **
  3. ***
  4. ****
  5. *****
  6. --
  7. *
  8. **
  9. ***
  10. ****
  11. *****
  12. ----
  13. *
  14. **
  15. ***
  16. ****
  17. *****

(8)continue

continue可以使得当前循环语句块中剩余未执行的语句被跳过,继续进行下一轮循环
例如:

  1. s1="No pain"
  2. s2="No gain"
  3. #s1、s2合并之后,判断如果当前字母为o,则不打印,进行下一轮循环
  4. for letter in s1+" "+s2 :
  5. if letter == 'o':
  6. continue
  7. print(letter, end="")

运行结果为:

  1. N pain N gain

(9) pass

pass是个空语句,什么都不做,只是为了占位,防止语法错误

(二)字符串

(1)定义

字符串是Python中常见的数据类型,创建字符串,只需要以如下变量赋值形式创建即可

  1. 变量名="字符串"
  2. 例如:
  3. s1 = "Work hard"

(2)引用

Python中引用字符串,可以使用索引值的形式,例如:

  1. #索引序列从0开始排序,左闭右开
  2. s1 = "No Pain No gain!"
  3. print("s1=%s" % s1[1:5])
  4. #初值缺省,默认为0
  5. print("s1=%s" % s1[:5])
  6. #终值缺省,默认为最后一个字符
  7. print("s1=%s" % s1[6:])
  8. #第三个值为步长,步长可以为负值
  9. print("s1=%s" % s1[6:2:-1])
  10. #初值、终值也可以为负值,负值意味着从右边第一个字符开始数,-1开始以此类推
  11. print("s1=%s" % s1[-2:-6:-1])
  12. #终值省略,且步长为负数,则默认终值为第一个字符位置
  13. print("s1=%s" % s1[-2::-2])
  14. #终值省略,且步长为正数,则默认终值为最后一个字符位置
  15. print("s1=%s" % s1[-2::2])
  16. #初值,终值都省略,步长为1,则为倒序输出字符串
  17. print("s1=%s" % s1[::-1])

运行结果为

  1. s1=o Pa
  2. s1=No Pa
  3. s1=n No gain!
  4. s1=niaP
  5. s1=niag
  6. s1=na Nna N
  7. s1=n
  8. s1=!niag oN niaP oN

(3)字符串运算

1)运算符

    • 字符串连接
    • 重复输出字符串
  • in 判断是否包含指定子串
  • not in 判断是否不包含指定子串
  • r/R 原始字符输出,不当做转义字符对待

2)举例

  1. #判断s2是否包含s1,是则输出"Miao",否则输出"Wang"
  2. s1 = "Hello"
  3. s2 = "Hello kitty"
  4. if s1 in s2 :
  5. print("Miao")
  6. else:
  7. print("Wang")

运行结果为:

  1. Miao

再者:

  1. #如果以r开头,则\n原样输出,不作处理,否则是换行的转义符
  2. print(r'a\n')
  3. print('a\n')
  4. #以R开头,则\t原样输出,不作处理
  5. print(R'a\tb')
  6. print('a\tb')

运行结果为:

  1. a\n
  2. a
  3. a\tb
  4. a b

(三)列表

(1)列表的创建

列表是python中最基本的数据结构,序列中的每个元素都分配一个数字,从0开始依次排序,可以称之为索引值
创建一个列表,可以采用如下形式:

  1. 列表名称= [列表项1,列表项2,列表项3...]
  2. 例如:
  3. list1 = ["我们","爱","科学"]
  4. list2 = [1,2,3,4,5]

(2)列表值的引用

类似于字符串,列表中值也可以通过列表名[索引值]的形式加以引用,以下是几个例子

  1. list1 = ["People", "sir,", "we", "should", "let", "them", "know!"]
  2. list2 = ["It", "will", "take", "more", "than", "that"]
  3. #序列从0开始,左闭右开
  4. print("list1=%s" % list1[1:5])
  5. #初值缺省默认为0
  6. print("list1=%s" % list1[:5])
  7. #终值缺省默认为最后的位置
  8. print("list1=%s" % list1[3:])
  9. #步长可以为负数
  10. print("list1=%s" % list1[6:2:-1])
  11. #初值、终值也可以为负数,意味着从最后倒数,-1开始
  12. print("list1=%s" % list1[-2:-6:-1])
  13. #步长为负数,且终值缺省,则终值默认为起始位置
  14. print("list1=%s" % list1[-2::-2])
  15. #步长为证书,且终值缺省,则默认终值为最后位置
  16. print("list1=%s" % list1[-2::2])
  17. #步长为-1,且初值、终值均缺省,则为倒序输出
  18. print("list1=%s" % list1[::-1])

运行结果为:

  1. list1=['sir,', 'we', 'should', 'let']
  2. list1=['People', 'sir,', 'we', 'should', 'let']
  3. list1=['should', 'let', 'them', 'know!']
  4. list1=['know!', 'them', 'let', 'should']
  5. list1=['them', 'let', 'should', 'we']
  6. list1=['them', 'should', 'sir,']
  7. list1=['them']
  8. list1=['know!', 'them', 'let', 'should', 'we', 'sir,', 'People']

(3)Python列表的运算

类似于字符串,Python列表同样也可以使用运算符进行运算

1)运算符

  • len() 返回列表的长度
    • 拼接两个列表
    • 重复列表
  • in 判断元素是否在列表中,或者用于对列表序列进行迭代
  • max()返回列表的最大值
  • min()返回列表的最小值
  • list()将元组转换为列表

2)举例

  1. list1 = ["People", "sir,", "we", "should", "let", "them", "know!"]
  2. list2 = ["It", "will", "take", "more", "than", "that"]
  3. #使用len()测量长度,并打印
  4. print("length of list:%d" % len(list1))
  5. print("length of list ['a',1,3+4j] is: {:d}".format(len(['a',1,3+4j])))
  6. #两个列表合并为一个,并打印
  7. list_a = list1 + list2
  8. print("list_a=%s" % list_a)
  9. #判断元素是否在列表中,并打印
  10. list3 = ["what"]
  11. list4 = ["what", "is", "it"]
  12. if list3[0] in list4:
  13. print("Done")
  14. else:
  15. print("Wrong")
  16. #将list1列表扩大为三倍原来元素的列表
  17. print(list1*3)

结果为:

  1. length of list7
  2. length of list ['a',1,3+4j] is: 3
  3. list_a=['People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'It', 'will', 'take', 'more', 'than', 'that']
  4. Done
  5. ['People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'People', 'sir,', 'we', 'should', 'let', 'them', 'know!']

再看一个关于最大值和最小值的例子:

  1. list1 = ["People", "sir,", "we", "should", "let", "them", "know!"]
  2. list2 = ["It", "will", "take", "more", "than", "that"]
  3. print("maximal item of list is: %s" % max(list1))
  4. print("Minimal item of list is: %s" % min(list1))

运行结果为

  1. maximal item of list is: we
  2. Minimal item of list is: People

(4)列表值的添加、修改和删除

1)列表值的添加

(i)append方法

在末尾添加新的值可以使用内置的append方法,例如:

  1. list1 = ["People", "sir,", "we", "should", "let", "them", "know!"]
  2. list2 = ["It", "will", "take", "more", "than", "that"]
  3. #list1增加一项
  4. list1.append("Warning")
  5. print("list1=%s" % list1)
  6. #list2增加一项
  7. list2.append(" !")
  8. print("list2={}".format(list2))
  9. #list1增加一项为列表,形成嵌套列表
  10. list1.append(["Maybe","it","is"])
  11. print("list1={}".format(list1))

运行结果为:

  1. list1=['People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'Warning']
  2. list2=['It', 'will', 'take', 'more', 'than', 'that', ' !']
  3. list1=['People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'Warning', ['Maybe', 'it', 'is']]

(ii)extend方法

使用extend方法,可以把一个整的序列转换为被操作列表的各个项,这点不同于append,append是将整个序列作为一个元素附加到原列表的后面。
例如:

  1. list1 = ["People", "sir,", "we", "should", "let", "them", "know!"]
  2. list2 = ["It", "will", "take", "more", "than", "that"]
  3. #注意,这时候extend附加的是一个字符串"Warning",而字符串会被视作一个序列,拆分成单个字符
  4. list1.extend("Warning")
  5. print("list1=%s" % list1)
  6. #如果指定附加的是一个列表,则指定列表中的每一项都会被附加到原来列表后面,成为一个新的项
  7. list1.extend(["regard"])
  8. print("list1=%s" % list1)
  9. #同理,空格和惊叹号都会被拆开
  10. list2.extend(" !")
  11. print("list2={}".format(list2))
  12. #列表中的每一个项会被拼接到原列表后面
  13. list1.extend(["Maybe","it","is"])
  14. print("list1={}".format(list1))

运行结果为:

  1. list1=['People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'W', 'a', 'r', 'n', 'i', 'n', 'g']
  2. list1=['People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'W', 'a', 'r', 'n', 'i', 'n', 'g', 'regard']
  3. list2=['It', 'will', 'take', 'more', 'than', 'that', ' ', '!']
  4. list1=['People', 'sir,', 'we', 'should', 'let', 'them', 'know!', 'W', 'a', 'r', 'n', 'i', 'n', 'g', 'regard', 'Maybe', 'it', 'is']

(iii)insert方法

insert方法可以将特定值插入到指定列表中的指定位置,其格式如下:

  1. list.insert(index,obj)

举例如下:

  1. #在指定位置插入"not",此时not作为一个整体插入到了指定位置,而原来的元素依次后退
  2. list3=["He","always","holds","charming","for","little","girls"]
  3. list3.insert(2, "not")
  4. print("list3={}".format(list3))
  5. #同样,如果我们指定插入一个列表,则指定列表会作为一个整体插入到对应的位置,形成嵌套列表,而不像extend,会对列表进行打散的处理
  6. list4=["Love", "me,", "love", "my", "dog"]
  7. list4.insert(1, ["baby", "not"])
  8. print("list4={}".format(list4))

运行结果如下:

  1. list3=['He', 'always', 'not', 'holds', 'charming', 'for', 'little', 'girls']
  2. list4=['Love', ['baby', 'not'], 'me,', 'love', 'my', 'dog']

2)列表项的修改

举例:

  1. list1=[1,3,5,7,9]
  2. #修改列表第一个元素的值为100
  3. list1[0]=100
  4. #修改列表最后一个元素的值为200
  5. list1[-1]=200
  6. print("list1={}".format(list1))

运行结果为:

  1. list1=[100, 3, 5, 7, 200]

3)列表项删除

(i)del函数删除

格式:del 列表项
如:

  1. list5 = ["Where", "there's", "a", "will,", "there", "is", "a", "way"]
  2. del(list5[1])
  3. print("list5={}".format(list5))
  4. #删除倒数第一个、第二个元素,如果不指定步长,默认为1
  5. del(list5[-1:-3:-1])
  6. print("list5={}".format(list5))

运行结果为:

  1. list5=['Where', 'a', 'will,', 'there', 'is', 'a', 'way']
  2. list5=['Where', 'a', 'will,', 'there', 'is']

(ii)pop方法

list.pop方法用于移除列表中的一个元素(默认为最后一个元素),并返回该元素的值
格式: list.pop(obj=list[-1])
例如:

  1. #没有指定索引序列号,则默认为移除最后一个字符
  2. list6 = ["Marriage", "is", "a", "lottery"]
  3. get_last_item = list6.pop()
  4. print("list6={}".format(list6))
  5. print("Get_last_item={}".format(get_last_item))
  6. #指定索引序列号,则移除指定的项目,并将此项目的值作为函数的返回值返回
  7. list7 = ["There", "is", "no", "accounting", "for", "tastes"]
  8. print("list7.pop(3)={}".format(list7.pop(3)))
  9. print("list7={}".format(list7))

运行结果为:

  1. list6=['Marriage', 'is', 'a']
  2. Get_last_item=lottery
  3. list7.pop(3)=accounting
  4. list7=['There', 'is', 'no', 'for', 'tastes']

(iii)remove方法

remove方法需要指定值,本方法可以移除列表中指定值的第一个匹配项
例如:

  1. #两个“sooner”,第一个被remove方法删掉了
  2. list8=["The", "sooner", "begun,", "the", "sooner", "done"]
  3. list8.remove("sooner")
  4. print("list8={}".format(list8))

结果为:

  1. list8=['The', 'begun,', 'the', 'sooner', 'done']

(IV)clear方法

clear方法用于清空列表,很方便
例如:

  1. list9=["They", "will", "all", "be", "wiped", "out", "from", "the", "Earth"]
  2. print("list9={}".format(list9))
  3. list9.clear()
  4. print("list9={}".format(list9))

结果为

  1. list9=['They', 'will', 'all', 'be', 'wiped', 'out', 'from', 'the', 'Earth']
  2. list9=[]

(5)Python列表的统计、排序、复制和查找

1)python列表的复制

(i)copy内置方法
  1. #注意:类似list10=list9之类的复制是无效的,这么定义,只是定义了一个指向list9的指针list10
  2. list9=["They", "will", "all", "be", "wiped", "out", "from", "the", "Earth"]
  3. print("list9={}".format(list9))
  4. list10=list9.copy()
  5. list9.clear()
  6. print("list9={}".format(list9))
  7. print("list10={}".format(list10))

运行结果为:

  1. list9=['They', 'will', 'all', 'be', 'wiped', 'out', 'from', 'the', 'Earth']
  2. list9=[]
  3. list10=['They', 'will', 'all', 'be', 'wiped', 'out', 'from', 'the', 'Earth']

(ii)list[:]格式的复制
  1. list9=["They", "will", "all", "be", "wiped", "out", "from", "the", "Earth"]
  2. print("list9={}".format(list9))
  3. list10=list9[:]
  4. list9.clear()
  5. print("list9={}".format(list9))
  6. print("list10={}".format(list10))

运行结果为:

  1. list9=['They', 'will', 'all', 'be', 'wiped', 'out', 'from', 'the', 'Earth']
  2. list9=[]
  3. list10=['They', 'will', 'all', 'be', 'wiped', 'out', 'from', 'the', 'Earth']

2)排序和倒序

(i)sort方法排序

例如:

  1. list11=[0,8,6,23,33,89,12,255,7]
  2. list11.sort()
  3. print("list11={}".format(list11))
  4. #reverse=True为降序排列
  5. list11.sort(reverse=True)
  6. print("list11={}".format(list11))

结果为:

  1. list11=[0, 6, 7, 8, 12, 23, 33, 89, 255]
  2. list11=[255, 89, 33, 23, 12, 8, 7, 6, 0]

(ii)reverse倒序输出

例如:

  1. list11=[0,8,6,23,33,89,12,255,7]
  2. list11.reverse()
  3. print("list11={}".format(list11))

结果为:

  1. list11=[7, 255, 12, 89, 33, 23, 6, 8, 0]

3) count()计数

count方法用于统计某个元素在列表中的出现个数
例如:

  1. list12=["to", "to", "be", "or", "not", "to", "be"]
  2. #输出"be"在list12中出现的次数
  3. print(list12.count("be"))
  4. #输出"to"在list12中出现的次数
  5. print(list12.count("to"))

结果为:

  1. 2
  2. 3

4)index()查找位置的方法

index方法用于从列表中找到指定值的第一个匹配项的索引序号
例如:

  1. list9=["They", "will", "all", "be", "wiped", "out", "from", "the", "Earth"]
  2. print(list9.index("all"))

运行结果为

  1. 2

(四)作业

(1)代码

  1. # 初始化价格字典
  2. price={"原味冰奶茶":3,"香蕉冰奶茶":5,"草莓冰奶茶":5,"蒟蒻冰奶茶":7,"珍珠冰奶茶":7}
  3. # 初始化营业次数计数器
  4. count = 0
  5. # 初始化消费情况列表
  6. consumption_list = []
  7. # 初始化会员列表
  8. membership_list = []
  9. # 开始循环打印菜单
  10. while 1 == 1:
  11. flag = 0
  12. member_id = "Not VIP"
  13. print("{:^200} \n".format("Menu List"))
  14. print("{:<200}\n".format("我们向您提供以下各种口味的奶茶:"))
  15. print("{:<200}\n".format("1.原味冰奶茶,每杯3元"))
  16. print("{:<200}\n".format("2.香蕉冰奶茶,每杯5元"))
  17. print("{:<200}\n".format("3.草莓冰奶茶,每杯5元"))
  18. print("{:<200}\n".format("4.蒟蒻冰奶茶,每杯7元"))
  19. print("{:<200}\n".format("5.珍珠冰奶茶,每杯7元"))
  20. # 输入选择的口味
  21. choice=input("请输入数字1-5来选择对应的你喜欢的口味(1-5):")
  22. key_list=["1","2","3","4","5"]
  23. if choice not in key_list:
  24. print("Woops! 我们只售卖以上五种奶茶哦!新口味敬请期待!现在返回菜单!")
  25. continue
  26. # 输入选择的数量
  27. quantity=input("请输入你需要的数量(1-10):")
  28. quantity_list=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
  29. membercard_digit_list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
  30. if quantity not in quantity_list:
  31. print("数量输入错误,返回菜单")
  32. continue
  33. #输入VIP身份
  34. VIP=input("你是VIP顾客吗?(Y/N):")
  35. VIP_list=["y","n","Y","N"]
  36. if VIP not in VIP_list:
  37. print("VIP身份输入错误,返回菜单")
  38. continue
  39. discount=1
  40. identifier="不是"
  41. reduce = "未能享受"
  42. # 如果是VIP客户,要求输入五位会员卡号码,输入长度不是五位,或者不是纯数字,都将报错返回主菜单
  43. if VIP in ["Y","y"]:
  44. identifier = "是"
  45. member_id = input("请输入您的五位会员卡号码:")
  46. tmp = []
  47. tmp.extend(member_id)
  48. if len(tmp) != 5:
  49. print("会员卡号长度非法,返回菜单")
  50. continue
  51. for ch in tmp:
  52. if ch not in membercard_digit_list:
  53. print("会员卡号含非法字符,返回菜单")
  54. flag = 1
  55. break
  56. if flag == 1:
  57. continue
  58. if member_id not in membership_list:
  59. membership_list.append(member_id)
  60. else:
  61. discount = 0.9
  62. reduce = "享受了"
  63. #根据选择确定的对应的口味
  64. if choice=="1":
  65. key="原味冰奶茶"
  66. elif choice=="2":
  67. key="香蕉冰奶茶"
  68. elif choice=="3":
  69. key="草莓冰奶茶"
  70. elif choice=="4":
  71. key="蒟蒻冰奶茶"
  72. else:
  73. key="珍珠冰奶茶"
  74. # 营业次数加1
  75. count += 1
  76. # 计算应付总价
  77. total_payment=price[key]*int(quantity)*discount
  78. # 将本次消费情况记入列表
  79. consumption_list.append({"id":count, "member_id":member_id, "taste":key, "quantity":quantity, "price":price[key], "discount":discount, "total_payment":total_payment})
  80. # 打印最终的总价计算信息以及相关信息
  81. print("欢迎您,您是今天光临本店的第%d位客人" % count)
  82. print("您选择了{:5},单价为{:d}元,数量为{:2d}杯,您{}VIP用户,您{}九折优惠价".format(key,price[key],int(quantity),identifier,reduce))
  83. print("应付总价为:{:<10.2f}元".format(total_payment))
  84. # 为了便于观察,这里在每次成功售卖奶茶之后,都会打印出历史消费情况
  85. for item in consumption_list:
  86. print(item)
  87. input("请输入回车继续")
  88. # 本日营业满20次,则退出系统
  89. if count >= 20:
  90. print("今日已经闭店,欢迎您明天光临!")
  91. break

(2)运行结果

调试运行的时候,为了方便起见,仅将日营业次数设置为了4

  1. Menu List
  2. 我们向您提供以下各种口味的奶茶:
  3. 1.原味冰奶茶,每杯3
  4. 2.香蕉冰奶茶,每杯5
  5. 3.草莓冰奶茶,每杯5
  6. 4.蒟蒻冰奶茶,每杯7
  7. 5.珍珠冰奶茶,每杯7
  8. 请输入数字1-5来选择对应的你喜欢的口味(1-5):1
  9. 请输入你需要的数量(1-10):2
  10. 你是VIP顾客吗?(Y/N):Y
  11. 请输入您的五位会员卡号码:00021
  12. 欢迎您,您是今天光临本店的第1位客人
  13. 您选择了原味冰奶茶,单价为3元,数量为 2杯,您是VIP用户,您未能享受九折优惠价
  14. 应付总价为:6.00
  15. {'id': 1, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '2', 'price': 3, 'discount': 1, 'total_payment': 6}
  16. 请输入回车继续
  17. Menu List
  18. 我们向您提供以下各种口味的奶茶:
  19. 1.原味冰奶茶,每杯3
  20. 2.香蕉冰奶茶,每杯5
  21. 3.草莓冰奶茶,每杯5
  22. 4.蒟蒻冰奶茶,每杯7
  23. 5.珍珠冰奶茶,每杯7
  24. 请输入数字1-5来选择对应的你喜欢的口味(1-5):1
  25. 请输入你需要的数量(1-10):3
  26. 你是VIP顾客吗?(Y/N):Y
  27. 请输入您的五位会员卡号码:00021
  28. 欢迎您,您是今天光临本店的第2位客人
  29. 您选择了原味冰奶茶,单价为3元,数量为 3杯,您是VIP用户,您享受了九折优惠价
  30. 应付总价为:8.10
  31. {'id': 1, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '2', 'price': 3, 'discount': 1, 'total_payment': 6}
  32. {'id': 2, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '3', 'price': 3, 'discount': 0.9, 'total_payment': 8.1}
  33. 请输入回车继续
  34. Menu List
  35. 我们向您提供以下各种口味的奶茶:
  36. 1.原味冰奶茶,每杯3
  37. 2.香蕉冰奶茶,每杯5
  38. 3.草莓冰奶茶,每杯5
  39. 4.蒟蒻冰奶茶,每杯7
  40. 5.珍珠冰奶茶,每杯7
  41. 请输入数字1-5来选择对应的你喜欢的口味(1-5):1
  42. 请输入你需要的数量(1-10):5
  43. 你是VIP顾客吗?(Y/N):Y
  44. 请输入您的五位会员卡号码:00021
  45. 欢迎您,您是今天光临本店的第3位客人
  46. 您选择了原味冰奶茶,单价为3元,数量为 5杯,您是VIP用户,您享受了九折优惠价
  47. 应付总价为:13.50
  48. {'id': 1, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '2', 'price': 3, 'discount': 1, 'total_payment': 6}
  49. {'id': 2, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '3', 'price': 3, 'discount': 0.9, 'total_payment': 8.1}
  50. {'id': 3, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '5', 'price': 3, 'discount': 0.9, 'total_payment': 13.5}
  51. 请输入回车继续
  52. Menu List
  53. 我们向您提供以下各种口味的奶茶:
  54. 1.原味冰奶茶,每杯3
  55. 2.香蕉冰奶茶,每杯5
  56. 3.草莓冰奶茶,每杯5
  57. 4.蒟蒻冰奶茶,每杯7
  58. 5.珍珠冰奶茶,每杯7
  59. 请输入数字1-5来选择对应的你喜欢的口味(1-5):1
  60. 请输入你需要的数量(1-10):2
  61. 你是VIP顾客吗?(Y/N):Y
  62. 请输入您的五位会员卡号码:890987
  63. 会员卡号长度非法,返回菜单
  64. Menu List
  65. 我们向您提供以下各种口味的奶茶:
  66. 1.原味冰奶茶,每杯3
  67. 2.香蕉冰奶茶,每杯5
  68. 3.草莓冰奶茶,每杯5
  69. 4.蒟蒻冰奶茶,每杯7
  70. 5.珍珠冰奶茶,每杯7
  71. 请输入数字1-5来选择对应的你喜欢的口味(1-5):1
  72. 请输入你需要的数量(1-10):5
  73. 你是VIP顾客吗?(Y/N):0iuys
  74. VIP身份输入错误,返回菜单
  75. Menu List
  76. 我们向您提供以下各种口味的奶茶:
  77. 1.原味冰奶茶,每杯3
  78. 2.香蕉冰奶茶,每杯5
  79. 3.草莓冰奶茶,每杯5
  80. 4.蒟蒻冰奶茶,每杯7
  81. 5.珍珠冰奶茶,每杯7
  82. 请输入数字1-5来选择对应的你喜欢的口味(1-5):5
  83. 请输入你需要的数量(1-10):10
  84. 你是VIP顾客吗?(Y/N):Y
  85. 请输入您的五位会员卡号码:00022
  86. 欢迎您,您是今天光临本店的第4位客人
  87. 您选择了珍珠冰奶茶,单价为7元,数量为10杯,您是VIP用户,您未能享受九折优惠价
  88. 应付总价为:70.00
  89. {'id': 1, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '2', 'price': 3, 'discount': 1, 'total_payment': 6}
  90. {'id': 2, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '3', 'price': 3, 'discount': 0.9, 'total_payment': 8.1}
  91. {'id': 3, 'member_id': '00021', 'taste': '原味冰奶茶', 'quantity': '5', 'price': 3, 'discount': 0.9, 'total_payment': 13.5}
  92. {'id': 4, 'member_id': '00022', 'taste': '珍珠冰奶茶', 'quantity': '10', 'price': 7, 'discount': 1, 'total_payment': 70}
  93. 请输入回车继续
  94. 今日已经闭店,欢迎您明天光临!