python基本语法
文章目录
数据类型和变量 Data types and variables
标准数据类型 Standard data type
数值 Number
-
int 整型数据 整数
print(type(2),':',2)输出:
<class 'int'> : 2 -
float 浮点型 小数
print(type(3.14),':',3.14)输出:
<class 'float'> : 3.14 -
complex 复数
形如 a + b j a+bj a+bj的数据
print(type(3+4j),':',3+4j)输出:
<class 'complex'> : (3+4j)
字符串 String
由一串字符组成(数字、字母、空格以及其他字符)
用" "或' '包围
print(type('python nb'),':','python nb')
print(type("python nb"),':',"python nb")
输出:
<class 'str'> : python nb
<class 'str'> : python nb
布尔 Boolean
取值:True、False
用于逻辑运算
print(type(True),':',True)
print(2>3)
输出:
<class 'bool'> : True
False
注:python严格区分大小写,True与False第一位均为大写!
真值测试
注意啦!!!!!!!!!!!!!!!!!!
这里着重强调!!python的真值判断!!!!与众不同!!!
首先说在python中,万物皆可Boolean!!!!
这句话的意思是,无论是python的内置对象还是自定义类的对象都可转换成Booelan值,也就是说,都有对应的真值!!!!!!!
python 官方文档镇楼!!!!!!!!!!!!!!!!!
Truth Value Testing
Any object can be tested for truth value, for use in an
iforwhilecondition or as operand of the Boolean operations below.By default, an object is considered true unless its class defines either a
__bool__()method that returnsFalseor a__len__()method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:
- constants defined to be false:
NoneandFalse.- zero of any numeric type:
0,0.0,0j,Decimal(0),Fraction(0, 1)- empty sequences and collections:
'',(),[],{},set(),range(0)Operations and built-in functions that have a Boolean result always return
0orFalsefor false and1orTruefor true, unless otherwise stated. (Important exception: the Boolean operationsorandandalways return one of their operands.)
看不懂木得关系,我给大家解释一下:
他就是说,python中所有的对象都有真值,都能放在if或while语句中
然而,他们的真值是怎么来的呢?原来python类中有这么两个魔术方法(魔术方法我个人感觉类似于java中的toString()方法,就是会隐式调用)——一个是返回布尔类型的__bool__()方法,一个呢是返回整形的_len_()方法(很显然,返回长度!);那么就是靠这两个方法,只需要看他们的返回值就能决定对象的真值(返回0 或False假,1或True为真)
还有除了一下几种为Fasle的情况,剩下的都为True:
- 定义为false的常量:
None和False。 - 任何为零的数值类型:
0,0.0,0j,Decimal(0),Fraction(0, 1) - 空序列和集合:
'',(),[],{},set(),range(0)
稍微总结一下就是:非假即真!一切与0有关的都为假(比如数值0,长度为0)
两个魔术方法的官方文档再次镇楼!!!!!!!!
object.``__bool__(self)Called to implement truth value testing and the built-in operation
bool(); should returnFalseorTrue. When this method is not defined,__len__()is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither__len__()nor__bool__(), all its instances are considered true.
object.``__len__(self)Called to implement the built-in function
len(). Should return the length of the object, an integer>=0. Also, an object that doesn’t define a__bool__()method and whose__len__()method returns zero is considered to be false in a Boolean context.CPython implementation detail: In CPython, the length is required to be at most
sys.maxsize. If the length is larger thansys.maxsizesome features (such aslen()) may raiseOverflowError. To prevent raisingOverflowErrorby truth value testing, an object must define a__bool__()method.
列表 List
- 序列类型(可迭代,序列表示索引为非负整数的有序对象集合,字符串也算序列,上面忘说了,嘤嘤嘤)
- 可变序列
[data, data, data,...]
a = [1, 2, 3, 4, 5]
a[0]
c = [1, 'a', True, 1.0]
print(c[3])
输出:
1
True
元组 Tuple
- 序列类型
- 不可变系列(元素不支持修改)
(data, data, data,...)
b = (1, 2, 3, 4, 5)
print(b[0])
c = (1, 'a', True, 1.0)
print(c[3])
输出:
1
True
字典 Dictionary
- 映射类型(key-value,“键”-“值”对,类似于java的HashMap)
{key1: value1, key2: vaule2,...}
son = {201701: '小黑', 201702: '小强'}
print(son[201701])
dic = {1001: '小黑', 1002: True, "错误": False}
print(dic["错误"])
输出:
小黑
False
集合 Set
- 无序,元素不充分(类似于java的Set)
{data1, data2, data3,...}
s = {'小明', '小红', '小明', 192, 198.1, 192, True, False, False}
print(s)
print(s[0])
输出:
{192, True, False, '小明', 198.1, '小红'}
----------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-7d2aee10af49> in <module>()
1 s = {'小明', '小红', '小明', 192, 198.1, 192, True, False, False}
2 print(s)
----> 3 print(s[0])
TypeError: 'set' object does not support indexing
变量 Variables
与其他语言基本一致,就是不需要声明类型,直接赋值,比如:
a = 3
而不是:
int a = 3;
而且python中不存在x++操作,应使用x += 1
还有就是python中存在打包赋值
x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)
1 2
2 1
另外命名最好符合规范,增加代码可读性,像:
- 不能数字开头
- 不能出现空格
- 不能与python保留字相同。
比较好的命名规范:
- 变量名由多个单词组成,单词之间用_连接
- 类目多个单词,每个单词首字母大写
- 常量所有首字母大写
控制流程
-
顺序(不讲!任性)
-
循环
-
遍历:
for元素in可迭代对象: 语句
顺便说一下
for i in range(3)相当于for (int i = 0; i < 3' i++)for i in range(1, 5)相当于for (int i = 1; i < 5; i ++) -
while
while条件: 语句
res = 0 for i in [1,2,3,4,5]: # 每次迭代,取出一个i res += i # 对每次迭代取出的i 进行相应操作 print(res) # 遍历结束后,执行后续语句 while res>8: res -= 1 print(res)15 8
-
-
分支
if 条件:
条件为真,执行
else :
条件为假,执行
或者
if 条件1:
条件1为真,执行
elif 条件2:
条件1为假的条件下,条件2为真,执行
else:
上述条件都为假,执行
money = 15 if money < 10: print('买的起') else: print('买不起') if money < 10: print('买的起') elif money <= 15: print('用花呗') else: print('彻底买不起')买不起 用花呗
输入输出
-
input():动态交互输入x = input("请输入一个数字:") print(x) print(type(x))请输入一个数字:44 <class 'str'>可以看出,
input()方法返回的是字符串。也就是说,无论我们输入的什么都会被当做字符串处理 -
eval()上面说到
input()方法返回的是字符串,那么我们要输入数值类型怎么办,就用eval()去除引号y = eval(input("请输入一个数字:")) print(y) print(type(y))请输入一个数字:4 4 <class 'int'> -
print():打印输出相当于
java的System.out,println(),默认自动换行。for i in range(1,5): print(i)1 2 3 4若不向自动换行,则用换行控制
end =for i in range(1,6): if i == 5: print(i) else: print(i, end = ' ') print('hahaha',end = ' 你哈哈个锤子 ') print('嘤嘤嘤')1 2 3 4 5 hahaha 你哈哈个锤子 嘤嘤嘤 -
format():格式化输出方法“字符{0: 修饰}字符{1: 修饰}字符.format(v0,v1)”
可以没有修饰,没有修饰就是将后面的参数填入前面对应的大括号内,v0填进0,v1填进1,如果大括号内没有内容,则默认顺序为0123。
"四是{0},10是{1}".format(4, '十')Out[61]:
'四是4,10是十'"14是{},四十是{}".format('十四', 40)Out[63]:
'14是十四,四十是40'"不要把14说成{1},也不要把四十说成{0}".format('十四', 40)Out[63]:
'不要把14说成40,也不要把四十说成十四'"四是{0},10不是{0}".format(4, '十')"14是{},四十是{}".format('十四', 40)Out[63]:
'14是十四,四十是40'带修饰的:
修饰符优先级,越往上优先级越高:
- 引导符号 :
- 填充:用于填充的字符如* __等
- 对齐:<左对齐,<右对齐,^居中对齐
- 宽度:设定输出的宽度
- 数字千分位分隔符:数字千分位分隔符适用于整数和浮点数 ,
- .精度:浮点数:小数部分精度
字符串:最大输出长度 - 类型:整数类型:b,c,d,o,x,X
浮点类型:e,E,f,%
上案例:
# 填充 print("{0:_^20}".format('test')) 输出 -> ________test________ print("{0:*<30}".format('test')) 输出 -> test************************** # 数字千分位符 print("{0:,}".format(10000000)) 输出 -> 10,000,000 # 精度 print("{0:.3f}".format(3.1415926)) 输出 -> 3.142 # 百分数 print("{0:.1%}".format(0.818727)) 输出 -> 81.9% # 科学计数法 print("{0:.2e}".format(0.818727)) 输出 -> 8.19e-01 # 类型 print("二进制 {0:b},Unicode码 {0:c},十进制 {0:d},八进制 {0:o},十六进制 {0:x}".format(250)) 输出 -> 二进制 11111010,Unicode码 ú,十进制 250,八进制 372,十六进制 fa -
I/O 太累了,不写了,以后再说吧
PEP 8编码规范
话不多说,上链接:
PEP 8 – Style Guide for Python Code
给大家象征性的总结一下:
编码规范是为了增加代码可读性,但不要保持盲目,具体情况具体分析。
代码的布局靠缩进,4个字符,也就是一个Tab键(用空格缩进的代码是在蓝翔学的吗)
每行最大长度在79个字符之内,要不看不过来,太长了。
二元运算符前后有空格,并且前或后换行(看自己项目规定),逗号后有空格,混合运算低优先级有空格。
空行分隔函数(2)和类(2)还有方法(1)
UTF-8
要有注释
要有注解
注释分两种
# 这叫单行注释
'''
这叫多行注释
啊!
大海啊!
你都是水!
太累了!
告辞!
'''

浙公网安备 33010602011771号