python 基础之for循环有限循环
# range(3) 表示
>>> range(3) [0, 1, 2]
for循环
for i in range(3): print(i)
测试
0 1 2
打印1~100的奇数
for i in range(101): if i % 2 == 1: print('chenxi:',i)
测试
chenxi: 1 chenxi: 3 chenxi: 5 chenxi: 7 chenxi: 9 chenxi: 11 chenxi: 13 chenxi: 15 chenxi: 17 chenxi: 19 chenxi: 21 chenxi: 23 chenxi: 25 chenxi: 27 chenxi: 29 chenxi: 31 chenxi: 33 chenxi: 35 chenxi: 37 chenxi: 39 chenxi: 41 chenxi: 43 chenxi: 45 chenxi: 47 chenxi: 49 chenxi: 51 chenxi: 53 chenxi: 55 chenxi: 57 chenxi: 59 chenxi: 61 chenxi: 63 chenxi: 65 chenxi: 67 chenxi: 69 chenxi: 71 chenxi: 73 chenxi: 75 chenxi: 77 chenxi: 79 chenxi: 81 chenxi: 83 chenxi: 85 chenxi: 87 chenxi: 89 chenxi: 91 chenxi: 93 chenxi: 95 chenxi: 97 chenxi: 99
另一种方式
for i in range(1,101,2): #2步长 print('chenxi:',i)
测试
D:\python\python.exe D:/untitled/dir/for.py chenxi: 1 chenxi: 3 chenxi: 5 chenxi: 7 chenxi: 9 chenxi: 11 chenxi: 13 chenxi: 15 chenxi: 17 chenxi: 19 chenxi: 21 chenxi: 23 chenxi: 25 chenxi: 27 chenxi: 29 chenxi: 31 chenxi: 33 chenxi: 35 chenxi: 37 chenxi: 39 chenxi: 41 chenxi: 43 chenxi: 45 chenxi: 47 chenxi: 49 chenxi: 51 chenxi: 53 chenxi: 55 chenxi: 57 chenxi: 59 chenxi: 61 chenxi: 63 chenxi: 65 chenxi: 67 chenxi: 69 chenxi: 71 chenxi: 73 chenxi: 75 chenxi: 77 chenxi: 79 chenxi: 81 chenxi: 83 chenxi: 85 chenxi: 87 chenxi: 89 chenxi: 91 chenxi: 93 chenxi: 95 chenxi: 97 chenxi: 99 Process finished with exit code 0
用逻辑与条件判断,打印1-100,跳过50-70之间数字
for i in range(101): if i < 50 or i > 70: print(i)
测试
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
利用for循环判断加if判断,写登录程序
# 用户登录程序判断用户名密码 username = "chenxi" passwed = "testki" #h = 9 for i in range(3):#重试3次 user = input("用户名:") passi = input("密码:") if user == username and passi == passwed : print("登录成功")
break #跳出循环 else: if i < 2: print("用户名或密码错误") else: print("请重新登录")
测试-1
D:\python\python.exe D:/untitled/dir/for.py 用户名:jhj 密码:hghbj 用户名或密码错误 用户名:fvbn 密码:bhbnb 用户名或密码错误 用户名:gbhgjhbj 密码:jbj 请重新登录 Process finished with exit code 0
测试-2
D:\python\python.exe D:/untitled/dir/for.py 用户名:chenxi 密码:testki 登录成功 Process finished with exit code 0
利用for循环判断加if判断,写登录程序-2
username = "chenxi" passwed = "testki" passed_test = False for i in range(3): user = input("输入用户名:") passw = input("请输入密码:") if user == username and passw == passwed: print("登录成功") passed_test = True break else: print("登录失败") if not passed_test: print("不要脸")
测试-1
D:\python\python.exe D:/untitled/dir/for.py 输入用户名:iyghgh 请输入密码:gvhvhv 登录失败 输入用户名:ghfvhvh 请输入密码:jbjbj 登录失败 输入用户名:bhgbhjbj 请输入密码:hjhjh 登录失败 不要脸 Process finished with exit code 0
测试-2
D:\python\python.exe D:/untitled/dir/for.py 输入用户名:chenxi 请输入密码:testki 登录成功 Process finished with exit code 0
草都可以从石头缝隙中长出来更可况你呢