while循环

age = 0
while age < 5:
    age+=1
    print(age)

猜年龄

有3次机会,如果都没猜对;然后问是否继续猜,输入yes继续猜,输入其他退出

方法1:

while 1:
    age = 18
    c = 0
    jx = 'yes'
    while c < 3:
        c += 1
        n = int(input('年龄:'))
        if n == age:
            print('对了')
            break
        elif n > age:
            print('大了')
        elif n < age:
            print('小了')
    else:
        y = input("是否继续?yes/no")
        if y == 'yes':
            c = 0
        else:
            break

方法2:

age_of_oldboy = 18
count = 0
while count <3:
    guess_age = int(input("guess age:") )
    if guess_age == age_of_oldboy :
        print("yes, you got it. ")
        break
    elif guess_age > age_of_oldboy:
        print("think smaller...")
    else:
        print("think bigger!")
    count +=1
    if count == 3:
        countine_confirm = input("do you want to keep guessing..?")
        if countine_confirm != 'n':
            count =0
else:
    print("you have tried too many times..fuck off")

十位数数字比个位数数字小的数

对100以内的两位数,
请使用一个两重循环打印出所有十位数数字比个位数数字小的数,
例如,23(2 < 3)

num = 0
while num < 10:
    num += 1
for g in range(num):
    for s in range(num):
        if s < g and s != 0:
            print(s,g)

计算 1 + 2 + 4 + 8 + 16 + … 的前20项的和。

利用 while True 无限循环配合 break 语句

方法1:

x = 1
N = 1
d = 2
sum = 0
while True:
    sum = sum + x
    x = x * d
    N = N + 1
    if N > 20:
        break
print('1 + 2 + 4 + 8 + 16 + … 的前20项的和为:',sum)

方法2:

print(2**20-1)

test :

2020年奥运会比赛中,规则制定,有10个国家参赛
分别成绩为89,78,67,56,45,23,90,45,88,35
其中算出平均成绩(去掉最高分和最低分)
如果中国足球队的成绩在平均分之上,那么就可以参加小组赛
否则就会被淘汰

list = [89,78,67,56,45,23,90,45,88,35]
for i in range(1,len(list)):
    for j in range(0,len(list)-1):
        if list[j] > list[j+1]:
            list[j],list[j+1]=list[j+1],list[j]
a = list[1:-1]
s = 0
for x in a:
    s += x
b = (s / len(a))
c = float(input('请输入中国队分数:'))
if c > b:
    print('可以参加小组赛')
else:
    print('不可以参加小组赛')
Last modification:July 30th, 2020 at 10:23 pm
如果觉得我的文章对你有用,请随意赞赏