python-for循环

像while循环一样,for可以完成循环的功能。

在python中for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。

for循环的格式:

for 临时变量 in 列表或者字符串等可迭代对象:

循环满足条件时可执行的代码

# 自定义一个字符串
name = "itheima"
for c in name:
    print(c)
# 范围标识 range()
# range(1, 5)  数学中 [1, 5)
for i in range(0, 5):
    print("第%d次" % (i + 1))
    print("你好龟叔")
# 只是循环5次而已
# range(x) -> [0, x)
for i in range(5):
    print("第%d次" % (i + 1))
    print("你好龟叔")
for i in range(10):    #i是临时变量,其实是for i in(0,1,2,3,4,5,6,7,8,9)
    print("loop",i)

for-else

# for-else 配合使用 带for循环完成后 会走else中的代码
for i in range(5):
    print(i)
else:
    print("else")
# for循环中 如果执行了break else中的代码将不再执行
for i in range(5):
    print(i)
    if i == 2:
        break
else:
    print("else")

无论for-else 还是 while-else 如果在for循环中 或者 while循环中 没有执行break 待for循环 或者while结束后,会执行else中的代码

当for循环或者while循环中的break执行 else中的代码将不会执行

age_of_oldboy = 56
for i in range(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!")
else:
    print("you have tried too many times...!")

for下面的正常走完,才走else,不是正常走完,不走else

for i in range(0,10,2):
    print("loop",i)

2是每隔一个跳一个,相当于步长,默认1

age_of_oldboy = 56
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...!")

购物车程序练习:

product_list = [
    ('IPhone',5800),
    ('Mac Pro',9800),
    ('Starbuck Latte',31),
    ('Alex Python',81),
    ('Bike',800)
]
shopping_list = []
salary = input('Input your salary:')
if salary.isdigit():   #虽然是字符串,但是是数字,就返回true
    salary = int(salary)
#for item in product_list:
#    print(product_list.index(item)+1,item)
while True:
    for index,item in enumerate(product_list):  #enumerate把下标取出来
        print(index,item)
    user_choice = input("选择要买嘛?>>>:")
    if user_choice.isdigit():
        user_choice = int(user_choice)
        if user_choice < len(product_list) and user_choice >= 0:
            p_item = product_list[user_choice]
            if p_item[1] <= salary:  #买得起
                shopping_list.append(p_item)
                salary -= p_item[1]
                print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m"%(p_item,salary))
            else:
                print("\033[41;1m你的余额只剩[%s]啦\033[0m"%salary)
        else:
            print("product code [%s] is not exist!"%user_choice)
    elif user_choice == 'q':
        print("------- shopping list -------")
        for p in shopping_list:
            print(p)
        print("your current balance :",salary)
        exit()
    else:
        print("invalid option")