python for循环
1.基本语句
for n in range(1, 5): # 从1记到4并输出 print(n) # 从1开始每隔3个数记一次,记到20并输出(最后的一个数表示步长为3) for n in range(1, 20, 3): print(n)
eg:用户登陆系统(正确输入用户名和密码之后,结束;错三次之后,禁止再次输入并退出)
# ------------方法1------------------ _user = "tom" #用户名 _passwd = "abc123" #密码
pass_verification = False #标志位 for n in range(3): username = input("Username:") password = input("Password:") if username == _user and password == _passwd: print("welcome %s login...." % _user) pass_verification = True break # 跳出循环 else: print("Invalid username or password!") if not pass_verification: print("已经错三次了,双双小可爱") # ---------------方法2 ------------------ _user = "tom" _passwd = "abc123" for n in range(3): username = input("Username:") password = input("Password:") if username == _user and password == _passwd: print("welcome %s login...." % _user) break # 跳出循环 else: print("Invalid username or password!") else: # 只有当上面的for/while循环正常执行完成,中间没被打断,才会执行else下面的语句 print("已经错三次了,双双小可爱")