Python基础-1
1、变量
命名规则:字母和下划线开头、只允许有字母数字下划线、关键字不能声明为变量名
定义变量 variable = "values"
name = "Ethan Du"
print("My name is ", name)
2、字符编码
python2中不支持中文,非ASCII字符,需要开头声明字符编码,
-*- coding:utf-8 -*-
python3默认支持unicode字符编码
3、注释
单行注释 #
多行注释 ''' code '''
4、用户输入:默认输入都是字符
input()
username = input("Username: ")
password = input("Password: ")
print(username,password)
密文出入
import getpass
passwd = getpass.getpass("password:") (此功能在pychar中无法使用)
2.x中的raw_input与3.x中的input等同。(不要用2.x中的input)
5、格式化输入出
1、字符串拼接:占用多个内存块,效率低
2、%s:string %d:integer %f:float
info0 = ''' ------info of %s------ name:%s age:%s job:%s ''' % (,,age,job)
3、变量替代
info1 = '''
------info of {_name}------
name:{_name}
age:{_age}
job:{_job}
'''.format(_name=name, _age=age, _job=job)
= '------info of {_name}------\n' \
'name:{_name}\n' \
'passwd:{_passwd}\n' \
'-----------------------------'.format(_name=name,_passwd=passwd)
4、分隔符 sep end
name = "Ethan Du" name1 = "HAHA" print(name,name1,sep=' ',end='.') STDOUT:Ethan Du HAHA.
5、输出重定向
sys.stdout = (open('log.txt'),'a')
import sys
temp = sys.stdout
sys.stdout = open('log.txt','a')
print('test')
sys.stdout.close()
sys.stdout = temp
print('test')
6、if else流程判断
PS:1、注意if判断条件或else后的冒号:
2、严格缩进,区别子语句
3、python默认输入全为字符型
age = int(input('guess age: '))
if age == 50:
print('yes')
elif age > 50:
print('younger')
else:
print('older')
7、while循环
count = 0
while count != 10:
if count == 9:
print('count:',count)
else:
print(count)
count +=1
else:
print('count:',count)
8、字典:
dict = {'ethan':'haha','dyp':'aaa'}
调用
dict['ethan']
更新
dict['ethan'] = 'hhhaaa'
删除
del dict['ethan'] #删除key为ethan的元素
dict.clear() #删除dict的所有元素
del dict #删除dict字典
9、文件IO
打开文件
file = open('filename','r') #r:读,w:写,a:如果没有则创建写入文件 a+:如果没有则创建读写文件
读文件
temp = file.read()
temp = file.readline() #读取一行
temp = file.readlines() #读取每行
for str in file: #遍历文件
print(str)
写文件
file.write(str)
file.writelines(str) #多行写入
关闭文件
file.close()
常用写法:with 自动关闭
with open('file')
10、split()函数
str.split(str='', num=string.count(str))[n]
str:分隔符,默认为空格
num:分割次数,分割为num+1个字符串
[n]:表示选取第几个片段
print u.split('.',-1) #分割最多次(实际与不加num参数相同)
['www', 'doiido', 'com', 'cn']
u1,u2,u3 = u.split('.',2) #分割两次,并把分割后的三个部分保存到三个文件
print u1
www
print u2
doiido
print u3
com.cn
str="hello boy<[www.doiido.com]>byebye"
print str.split("[")[1].split("]")[0]
www.doiido.com
print str.split("[")[1].split("]")[0].split(".")
['www', 'doiido', 'com']
11、练习,登陆小程序
要求:输入用户名和密码,认证成功显示欢迎信息,输错三次锁定
流程图:
代码:
#Author:Ethan Du
count = 0
while True:
flag = 0
username = input('Username: ')
password = input('Password: ')
if username == '' or password == '':
print('Username or Password is empty, please input again')
continue
with open('user_file','r') as file:
for key in file:
if key.split()[0] == username and count != 3:
with open('lock_file','r') as lock:
for dlock in lock:
if dlock.split()[0] == username:
print('too much wrong login, exit')
exit()
if key.split()[1] == password:
print('Welcome to system')
flag = 1
exit()
else:
print('Wrong password, please input again')
count += 1
if count == 3:
with open('lock_file','w') as lock:
lock.write(username)
count = 0
print('too much wrong login, exit')
exit()
flag = 2
break
if flag == 0:
print('username is not exsit, please input correct username')
12、练习--多级菜单
流程图:

#Author:Ethan Du
zone = {
'北京':{
'城区':['一环','二环'],
'郊区':['通州','燕郊']
},
'山东':{
'济南':['历城','泺口'],
'青岛':['市南','崂山']
},
'湖北':{
'武汉':['武昌','汉口'],
'襄阳':['襄城','襄樊']
}
}
while True:
print('省'.center(20,'*'))
province = list(zone.keys())
for n,i in enumerate(province):
print('%d、%s' %(n,i))
choice = input('请选择:')
if choice.isdigit():
cho_pro = int(choice)
if cho_pro >= 0 and cho_pro < len(province):
while True:
city = list(zone[province[cho_pro]].keys())
print('市'.center(20,'*'))
for n,i in enumerate(city):
print('%d、%s' % (n, i))
choice1 = input('请选择:')
if choice1.isdigit():
cho_city = int(choice1)
if cho_city >= 0 and cho_city < len(city):
while True:
county = zone[province[cho_pro]][city[cho_city]]
print('县'.center(20,'*'))
for n,i in enumerate(county):
print('%d、%s' % (n,i))
choice2 = input('请选择:')
if choice2 == 'b':
break
elif choice2 == 'q':
quit()
elif choice1 == 'b':
break
elif choice1 == 'q':
quit()
else:
print('Error!!!input again')
elif choice == 'b':
continue
elif choice == 'q':
break
else:
print('Error!!!input again')

浙公网安备 33010602011771号