Python Day One
1.变量
变量不需要声明类型,默认str类型,若有需要的类型,必须强制转换类型
test = "Hello world"
name = "Kevin"
print(test,name)
2. 输入
name = input("name:")
age = int(input("age:"))
job = input("job:")
salary = input("salary:")
3.格式化
''' ''' 可以做注释也可以赋值给变量表示格式化字符串
方法1
info = '''
------ info of %s------
Name:%s
Age:%d
Job:%s
Salary:%s
'''%(name,name,age,job,salary)
方法2
info2='''
------ info of {_name}------
Name:{_name}
Age:{_age}
Job:{_job}
Salary:{_salary}
'''.format(_name = name,_age=age,_job=job,_salary=salary)
方法3
info2='''
------ info of {0}------
Name:{0}
Age:{1}
Job:{2}
Salary:{3}
'''.format(name,age,job,salary)
4.if...else
格式:
if a>b :
xxx
else:
xxx
注意:if 和 else 在这里要定格写,中间的语句要缩进 elif 表示 else if
_username = "Alex"
_password ="123"
username = input("username:")
password = input("password:")
if _username == username and _password == password :
print("Welcome user {user} login...".format(user=username))
else:
print("Invalid username or password!")
Python getpass 提供的getpass()方法可以实现密文输入
5.循环语句
<1> while循环
可以加else语句,表示不成立之后执行的代码块
count = 3
while count>0:
print("yes")
count-=1
else:
print("over")
<2> for循环
#打印 0 2 4 6 8
for i in range(0,10,2):
print(i)
#默认range(x,x,1)
6.课后作业
1.登录接口
2.输入用户名密码
3.输错三次锁定
#登录接口
#输入用户名密码
#输错三次锁定
import sys
#Author:Kevin
count = 1
t = True
while t:
rol = input("Register or Login ?(r/l/q)")
if rol =='r': #注册模块
username = input("Please input you username:")
time = "0"
#查找是否被注册
f = open("workfile",'r+')
for list in f:
if username ==list[0:len(username)] :
print("Already registered")
break
else:
password = input("enter password:")
f.write(username+" "+password+" "+time+"\n")
print("register successful ! ")
f.close()
elif rol=='l': #登录模块
while count <= 3:
f = open("workfile",'r+')
lock = "0"
username = input("Please input you username:")
for list in f:
# print(list[0:len(username)])
if username ==list[0:len(username)]:
#print(list[len(list)-2])
if list[len(list)-2]=="0":#查找user是否被锁定账户
password = input("enter password:")
#print(list[len(username)+1:len(list)-3])
if password ==list[len(username)+1:len(list)-3]:
print("success!")
break
else:
print("Invalid username or password!")
count+=1
break
else:
lock = "1"
break
else:
print("None register user !")
if(lock=="1"):
print("Locked!")
break
f.close()
else:
#超过三次错误给用户上锁
f=open("workfile",'r')
f_new=open("workfile(1)",'w')
f_new.truncate()
for i in f:
if username in i:
i = i.replace("0","1")
f_new.write(i)
f.close()
f_new.close()
f=open("workfile",'w')
f.truncate()
f_new=open("workfile(1)",'r')
for j in f_new:
f.write(j)
f.close()
f_new.close()
#通过对两个文件操作来修改文件内容
print("Locked !")
elif rol == 'q':#退出
t=False
运行结果: