python基础--循环语句

python基础--循环语句

1 概念

情景:

为了显示对恋人的喜爱,要重复打印5次 "亲爱的,我喜欢你。"

for i in range (0,最大次数,步长):

2 代码示例:

​ 显示0--21以内的被5整除的数字

# 用for 循环语句 打印 
>>> for i in range (0,21,5):
...   print(i)
...
0
5
10
15
20
# 用while 循环语句 打印 
>>> maxcount =21
>>> i =0
>>> while i < maxcount:
    print(i)
    i=i+5

3 总结

关键语法:

# 次数明确的时候
for index in range (开始位置,终止位置,增长步长):
    doing
# 条件明确的时候
while True:
    doing
else:
    doing
# break  和 continue  
pass  空结构体
break 跳出循环
continue 循环继续

4 脑洞大开

猜数字游戏,

猜数字游戏,

1 当输入非数字的时候,提示输入的不是数字,程序不退出,还可以继续输入。

2 当输入 不是正确的数字的时候,提示,猜的不对,请继续猜

3 最多猜10次,且会显示剩下几次机会猜数字。

4 猜对了,提示“你猜对了,游戏结束”,并且退出程序。

index = 0
max_index = 10
correct_number = str(8)
# for i in range(index, max_index, 1):
while index < max_index:

    get_age = input("Please input you number ")


    if not get_age.isdigit():
        print("输入的不是数字")

    elif get_age == correct_number:
        print("你猜对了,游戏结束!")
        break

    elif get_age != correct_number:
        print("你猜错了", "还可以进行的次数是", (max_index - index - 1))
        index += 1

    else:
        print("未知错误")

else:
    print("游戏未完成")

以下是另一种写法 不用str.isdigit()函数的时候需要用try ...except来包装。

index =0
max_index = 10
correct_number = 8

# for i in range(index, max_index, 1):
while index < max_index:

    try:
        get_age = int(input("Please input you number "))
        
        index += 1
        if get_age == correct_number:
            print("你猜对了,游戏结束")
            break

        elif get_age != correct_number:
            print("你猜错了", "还可以进行的次数是", (max_index - index - 1))

        else:
            print("未知错误")

    except:
        print("输入错误", "还可以进行的次数是", (max_index - index - 1))
        continue

猜你喜欢

转载自www.cnblogs.com/robert1949/p/11533195.html