
# 15.while循环
- rows = 0
- while rows < 5:
- print('*' * rows)
- rows += 1
- '''
- *
- **
- ***
- ****
- '''
# 16.使用while循环制作猜灯谜游戏
- secret_num = 12
- guess_count = 0
- guess_limit = 100
-
- while guess_count < guess_limit:
- guess_count = int(input("猜测:"))
-
- if guess_count == secret_num:
- print("你赢了!")
- break
- else:
- print("很抱歉,你失败了!")
- '''
- 猜测:10
- 很抱歉,你失败了!
- 猜测:12
- 你赢了!
- 进程已结束,退出代码为 0
- '''
// break:跳出循环。
# 17.打造汽车游戏
- command = ""
- started = False
-
- print("请输入help查看文档:")
- while True:
- command = input("> ").lower()
- if command == "start":
- if started:
- print("车辆已在运行中")
- else:
- started = True
- print("车辆开始运行...")
- elif command == "stop":
- if not started:
- print("车辆已经停下了")
- else:
- started = False
- print("车辆停止")
- elif command == "help":
- print("""
- start--车辆开始运行
- stop--车辆停止
- quit--退出
- """)
- elif command == "quit":
- print("退出系统!")
- break
- '''
- 请输入help查看文档:
- > help
- start--车辆开始运行
- stop--车辆停止
- quit--退出
-
- > start
- 车辆开始运行...
- > start
- 车辆已在运行中
- > stop
- 车辆停止
- > stop
- 车辆已经停下了
- > 1
- > quit
- 退出系统!
- '''
# 18.for循环
- # 对字符串进行循环
- for item in 'Pyn':
- print(item)
- '''
- P
- y
- n
- '''
- # 对字符串数组的循环
- for item in ['JoJo', 'Bob', 'Dou']:
- print(item)
- """
- JoJo
- Bob
- Dou
- """
- # 对数字进行循环(从0到结尾,不包含本身)
- for item in range(3):
- print(item)
- '''
- 0
- 1
- 2
- '''
- # 对数字进行循环(从指定的5到8(不包含8))
- for item in range(5, 8):
- print(item)
- '''
- 5
- 6
- 7
- '''
- # 对数字进行循环(从指定的1到9(不包含9),输出从1 +3递增的数列)
- for item in range(1, 9, 3):
- print(item)
- '''
- 1
- 4
- 7
- '''
练习:输入一个价格数组,将数组内的价格相加。
- prices = [12, 23, 56, 21]
- prices.sort() # 调用升序排序
- print(prices) # [12, 21, 23, 56]
- total = 0
-
- for price in prices:
- total += price
- print(total) # 112
# 19.嵌套循环(在循环内部制造循环),打印九九乘法表
- # 19.嵌套循环(在循环内部制造循环)
- numbers = [2, 3, 9, 4, 1]
- for x_count in numbers:
- print('x' * x_count)
- '''
- xx
- xxx
- xxxxxxxxx
- xxxx
- x
- '''
- for x_count in numbers:
- output = ''
- for count in range(x_count):
- output += 'x'
- print(output)
- '''
- xx
- xxx
- xxxxxxxxx
- xxxx
- x
- '''
// 练习 :打印九九乘法表
- for x in range(1, 10):
- for y in range(1, x+1):
- print(f'{x}*{y}={x * y}', end='\t')
- print()
- '''
- 1*1=1
- 2*1=2 2*2=4
- 3*1=3 3*2=6 3*3=9
- 4*1=4 4*2=8 4*3=12 4*4=16
- 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
- 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
- 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
- 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
- 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
- '''
// 注意:Python中可使用,end = " ",取消自动换行,或选择自己需要的结尾控制符号。