一、循环语句
1.for 语句
有限循环 ,次数限制
格式: for i in range (3):
例子:
_username = "zhichengfang"
_password = "fzc2551352"
for i in range(3) :
username = input("username :")
psworrd = input("password :")
if username == _username and psworrd == _password :
print("welcome login of %s"%_username)
break
else :
print("the username or password is wrong you will hve %s times"% str(2-i))
2. while 语句
无限循环=死循环
格式: while 条件 :
例子:
# _author : Administrator
# date : 2020/4/26 0026
_username = "zhichengfang"
_password = "fzc2551352"
counter = 1
while counter < 4:
username = input("username :")
psworrd = input("password :")
if username == _username and psworrd == _password :
print("welcome login of %s"%_username)
break
else :
print("the username or password is wrong ")
counter += 1
if counter == 4 :
try_again = input("try again? [y/n]")
if try_again == "y":
counter = 1
else:
print("get out my area, fuck you bitch")
3.break 、continue
continue 结束本次循环,继续下一次循环 ,continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后 继续 进行下一轮循环
例子:
#!/usr/bin/python
# Filename: continue.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
continue
print 'Input is of sufficient length'
break 跳出整个当前的循环
例子:
for i in range (3):
print(i)
for j in range (3):
print(j)
break #跳出当前循环,跳出第二层循环,第一层不受影响
4,常用占用符:
常见的占位符有:
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数
使用方法:
tpl= "i am %s" % "alex"
tpl= "i am %s age %d" % ("alex",18)
tpl= "i am %(name)s age %(age)d" % {"name":"alex","age":18}
tpl= "percent %.2f" % 99.97623
tpl= "i am %(pp).2f" % {"pp":123.425556, }
tpl= "i am %.2f %%" % {"pp":123.425556, }
例子:
name = input("name is :") #用户交互 input()
age= input("age is :")
job= input("job is :")
salary = input("salary is :")
msg = '''
---------info of %s---------
Name: %s
Age : %s
Job : %s
salary : %s
----------------------------
'''%(name,name,age,job,salary) #msg = 被赋值为字符串
print(msg)