作者:赵俊 发布日期:2019/10/18
一、第一个python程序
1、在解释器下写hello world程序运行,与运行外部文件方法
运行外部文件,必须在相应位置创建一个python文件,里面写上语句
2、#!/usr/bin/evn python的作用,告诉操作系统使用的解释器是什么
#!/usr/bin/python相当于写死了python路径;
#!/usr/bin/env python会去环境设置寻找python目录,推荐这种写法
二、变量
1、pycharm工程新建文件,模板代码设置
2、变量的内存管理
3、变量定义的规则
- 变量只能是字母、数字或下划线的任意组合
- 变量的第一个字符不能是数字
- 以下关键字不能声明为变量
['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、python解释器在加载 .py 文件中的代码时,会对内容进行编码(默认ascill)
ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言,其最多只能用 8 位来表示(一个字节),即:28 = 256,所以,ASCII码最多只能表示 255 个符号。
2、关于中文编码
简体中文的GB2312和用于繁体中文的big5
从ASCII、GB2312、GBK 到GB18030,这些编码方法是向下兼容的
3、国际编码
Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码
UTF-8,是对Unicode编码的压缩和优化,他不再使用最少使用2个字节,而是将所有的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个字节保存,东亚的字符用3个字节保存
4、# -*- coding: utf-8 -*-
python 2.x上写中文要告诉解释器编码格式
python 3.x支持unicode编码
四、用户输入及格式化输出
1、注释
单行注释:#号后面跟要注释的内容
多行注释:'''被注释内容''' 三个单引号或双引号都可以
多行注释可以用来打印多行,如下图,左侧为源码,右侧为输出
2、用户输入
1 username = input("请输入用户名") 2 password = input("请输入密码") 3 print(username,password)
3、格式化输出
用+号拼接字符串,不建议使用,占用内存多
1 name = input("请输入用户名") 2 age = input("请输入年龄") 3 info = ''' 4 ----------info of '''+name+'''---------- 5 name:'''+name+''' 6 age:'''+age 7 print(info)
用%s或%d或f%,%s是接收字符串的,%d是接收数值的,%f是接收浮点。input输入的均为字符串,所有在用%d时,必须用int()强制类型装换为整型
1 name = input("请输入用户名") 2 age = input("请输入年龄") 3 info = ''' 4 ----------info of %s---------- 5 name:%s 6 age:%s 7 '''%(name,name,age) 8 print(info)
使用format格式化输出
1 name = input("请输入用户名") 2 age = input("请输入年龄") 3 info = ''' 4 ----------info of {_name}---------- 5 name:{_name} 6 age:{_age} 7 '''.format(_name=name,_age= age) 8 print(info)
使用format格式化输出另一种
1 name = input("请输入用户名") 2 age = input("请输入年龄") 3 info = ''' 4 ----------info of {0}---------- 5 name:{0} 6 age:{1} 7 '''.format(name,age) 8 print(info)
控制台输出文字带颜色
说明: 前景色 背景色 颜色 --------------------------------------- 30 40 黑色 31 41 红色 32 42 绿色 33 43 黃色 34 44 蓝色 35 45 洋红 36 46 青色 37 47 白色 显示方式 意义 ---------------------------------- 0 终端默认设置 1 高亮显示
22 非高亮显示 4 使用下划线
24 去下划线 5 闪烁
25 去闪烁 7 反白显示
27 非反显 8 不可见
28 可见
语法格式 033[1;31;40m: 代表接下来输出内容为:高亮显示,前景色为红色,背景色被黑色。[ 与 m 之间参数的顺序可以颠倒,可以省略 033[0m:代表接下来的输入内容为终端默认设置,也就是取消之前的颜色设置,如果没有这个,接下来的输出,都是上面的设置。 例子: print('