基础知识

当循环次数不确定,循环变量的变化轨迹不那么明晰时,while循环就成了不二之选。

格式:   while  条件表达式 :

使用while循环,进入循环前必须对循环变量做初始化,离开循环提前必须对循环变量做出处理,比如递增或递减,对死循环要严防死守!

while循环一定得老老实实等到条件表达式为假后才能逃离么?

答案是NO,请把镁光灯打向break

break语句退出整个循环;continue语句推出本轮循环,是否继续循环要看while后面条件表达式的心情好不好。

最后我们用刚学会的while循环和for循环打了套组合拳,共同在屏幕上打印出来一棵松树,

树冠的高度由你来决定

# ---------- PROBLEM : DRAW A PINE TREE ----------
# For this problem I want you to draw a pine tree after asking the user
# for the number of rows. Here is the sample program

"""
How tall is the tree : 5

    #
   ###
  #####
 #######
#########
    #
    
"""
'''
Patterns:
4 spaces : 1 hash
3 spaces : 3 hash
2 spaces : 5 hash
1 spaces : 7 hash
0 spaces : 7 hash
loop times = tree_height
spaces decrement by 1
hashes increment by 2
spaces before stump = 4
'''

# Get the number of rows for the tree
tree_height = input("How tall is the tree: ")

# Convert into an integer
tree_height = int(tree_height)

# initiate the spaces
spaces = tree_height - 1

# initiate the hashes
hashes = 1

# stump_spaces
stump_spaces = tree_height - 1

# While loop times equal to tree_height
while tree_height != 0:

	# print the spaces
	for i in range(spaces):
		print(' ', end='')

	# print the hashes
	for i in range(hashes):
		print('#', end='')
	# print('#' * hashes, end='')

	# Newline after each row is printed
	print()

	# spaces decremented by 1
	spaces -= 1

	# hashes incremented by 3
	hashes += 2

	# tree_height decremented by 1
	tree_height -= 1

# print the spaces before the stump
for i in range(stump_spaces):
	print(' ', end='')

# then the hash
print("#")

视频链接:
 

1 1 1 1 1 1 1 1 1 1 Rating 3.20 (5 Votes)