开发者学堂课程【Python入门 2020年版:嵌套打印三角形】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/639/detail/10271
嵌套打印三角形
嵌套打印三角形
打印一个星星不换行:
print(‘*’, end=’ ‘)
运行结果:
C:\Users\chris\AppData\Local\Programs\Python\Python37\python.exe C:/Users/chris/Desktop/Python 基础/Day04-流程
*
Process finished with exit code 0
打印五个星星不换行:
i = 0
while i < 5:
i += 1
print(‘*’, end=’ ‘)
运行结果:
C:\Users\chris\AppData\Local\Programs\Python\Python37\python.exe C:/Users/chris/Desktop/Python 基础/Day04-流程
* * * * * *
Process finished with exit code 0
现想换行:
i = 0
while i < 5:
i += 1
print(‘*’, end=’ ‘)
print()
#外循环用来控制行数
#内循环用来控制列数
j = 0
while j < 5:
j += 1 # j =1
i = 0
while i < 5:
i += 1
print(‘*’), end=’ ‘)
print()
运行结果:
C:\Users\chris\AppData\Local\Programs\Python\Python37\python.exe C:/Users/chris/Desktop/Python 基础/Day04-流程
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
Process finished with exit code 0
改每一列的个数 i,j 是行数。
现要打印三角形:
j = 0
while j < 5:
j += 1 # j =1
i = 0
while i < 5:
i += 1
print(‘*’), end=’ ‘)
print()
对于第一行星星,j=1。打印完5个星星后开始换行,到下一行后在回来,j<5,j=1满足条件小于5,j=2。I 又从0开始又打印5个星星。第二行星星 j=2。第三行星星 j=3。第四行星星 j=4。第五行星星 j=5。所以把 i 换成 j
j = 0
while j < 5:
j += 1 # j =1
i = 0
while i < j:
i += 1
print(‘*’), end=’ ‘)
print()
因为 j 就是星星所需的个数。
运行结果:
C:\Users\chris\AppData\Local\Programs\Python\Python37\python.exe C:/Users/chris/Desktop/Python 基础/Day04-流程
*
* *
* * *
* * * *
* * * * *
Process finished with exit code 0
九九乘法表是就行,所以把j改成九。
j = 0
while j < 5:
j += 1 # j =1
i = 0
while i < j:
i += 1
print(‘*’), end=’ ‘)
print()
运行结果:
C:\Users\chris\AppData\Local\Programs\Python\Python37\python.exe C:/Users/chris/Desktop/Python 基础/Day04-流程
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
Process finished with exit code 0