while循环实例
Posted evatan123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了while循环实例相关的知识,希望对你有一定的参考价值。
输出1到100之间的偶数:
num = 1 while num <= 100: if num%2 == 0: print(num) num += 1
猜年龄:
age = 50 #user_input_age = int(input("Age is:")) flag = True while flag: user_input_age = int(input("Age is:")) if user_input_age == age: print("Yes") flag = False elif user_input_age > age: print("Is bigger.") else: print("Is smaller") print("End")
continue statement:
num = 1 while num <= 10: num += 1 if num == 3: continue print(num) else: print("This is else statement")
break statement:
num = 1 while num <= 10: num += 1 if num == 5: break print(num) else: print("This is else statement")
三行转换成一行:
print("Hello world", end="") print("Hello world", end="") print("Hello world", end="")
while语句嵌套:
num1 = 0 while num1 <= 5: print(num1, end = "_") num2 = 0 while num2 <= 7: print(num2, end = "-") num2 += 1 num1 += 1 print()
while语句嵌套小练习:使用#输出长方形,用户可以定义长度和宽度
height = int(input("Height:")) width = int(input("Width:")) num_height = 1 while num_height <= height: num_width = 1 while num_width <= width: print("#", end = "") num_width += 1 print() num_height +=1
以上是关于while循环实例的主要内容,如果未能解决你的问题,请参考以下文章