1.1 变量定义
在Linux下,需要加上环境变量,申明解释器
#!/usr/lib/env python
print(“hello world!”)
变量定义的规则:
- 变量名只能是 字母、数字或下划线的任意组合
- 变量名的第一个字符不能是数字
- 以下关键字不能声明为变量名
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
变量的赋值
1 name = "Alex Li" 2 3 name2 = name 4 print(name,name2) 5 6 name = "Jack" 7 8 print("What is the value of name2 now?")
变量名最好有一定的含义:如name,age。最好不要是汉语或者拼音。
1.2 字符编码
ASSIC 255 1bytes
1980 gb2312 7000多汉字--->1994 GBK1.0 2W多汉字-->2000 GB18030 2.7W汉字(少数民族)
Unicode 2bytes 定长
UTF-8 变长 en:1byte,zh:3bytes
要想在Python2.X中写中文,必须先申明编码
#-*- coding:utf-8
name=”周琼杰”
print(name)
1.3 注释
单行注释:开头使用#
多行注释:前后三个引号(单引号’’’和双引号”””都可以)
1.4 交互输入
1 username = input("username=") 2 passwd = input("passwd=") 3 print(username,passwd)
标准库:Python中自带的库
将密码设置为密文:
1 import getpass #引入getpass模块 2 3 username = input("username=") 4 5 passwd = getpass.getpass("passwd=") #使用加密认证 6 7 print(username,passwd)
对用户名密码进行认证:
1 _username = 'zhou' 2 3 _passwd = 'abc123' 4 5 username = input("username=") 6 7 passwd = input("passwd=") 8 9 if _username == username and _passwd == passwd: 10 11 print("Welcome user {name} login..." .format(name=username)) #格式化打印 12 13 else: 14 15 print("invalid username or passwd")
1.5 字符串拼接
1、用加号(+)拼接
1 age = input("age=") 2 job = input("job=") 3 salary = input("salary=") 4 info = ''' 5 ----------- info of ''' + name + '''------ 6 name:''' + name + ''' 7 age:''' + age + ''' 8 job:''' + job + ''' 9 salary:''' + salary 10 11 print(info)
2、用占位符(%)拼接
1 age = input("age=") 2 job = input("job=") 3 salary = input("salary=") 4 info = ''' 5 ----------- info of %s------ 6 name:%s 7 age:%s 8 job:%s 9 salary:%s 10 '''%(name,name,age,job,salary) 11 12 print(info)
3、用format函数拼接
①关键字拼接也是官方推荐
1 name = input("username=") 2 age = input("age=") 3 job = input("job=") 4 salary = input("salary=") 5 info = ''' 6 ----------- info of {_name}------ 7 name:{_name} 8 age:{_age} 9 job:{_job} 10 salary:{_salary} 11 ''' .format(_name=name, 12 _age=age, 13 _job=job, 14 _salary=salary) 15 16 print(info)
②占位符拼接
1 name = input("username=") 2 age = input("age=") 3 job = input("job=") 4 salary = input("salary=") 5 info = ''' 6 ----------- info of {0}------ 7 name:{0} 8 age:{1} 9 job:{2} 10 salary:{3} 11 ''' .format(name,age,job,salary) 12 13 print(info)