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 <= 
        print("#", end = "")
        num_width += 1
    print()
    num_height +=1

 while语句输出九九乘法表:

#九九乘法表
first = 1
#second = 9

while first <= 9:
    #print (str(first) + "*" + str(first) + "=", first)
    second = 1
    while second <= first :
        print ( str(second) ,"*" ,str(first), "=" , second * first , end = "	")
        second += 1
    print()
    first += 1
原文地址:https://www.cnblogs.com/evatan123/p/9186985.html