Python基础第一课

变量、运算符与数据类型

1. 注释

单行注释用: #
区间注释用: ‘’’ ‘’’ 或者 “”" “”"

!= Foo。

2. 变量

一些约定俗成的命名规则

  • 全大写的变量名一般认为是符号常量
  • 尽量避免下划线开头的变量名,特别是双下划线。(因为下划线对解释器有特殊的意义,是内建标识符使用的符号,一般会把这类变量名当作私有的)
  • 最好不要用汉语拼音命名,要做到见名识义
  • 当用几个单词组合成一个变量名时,一般有两种方式:1. 驼峰式(第一个单词小写,后续单词首字母大写。如:stuName)2.下划线式。如:stu_name。)
  • 关键字不能用于变量命名。如:and, in,…

关键字

关键字是python的关键组成部分,不可随便所谓其他对象的标识符

  • 在一门语言中关键字是基本固定的组合
  • 在IDE中常以不同颜色字体出现

【例子】

import keyword
print(keyword.kwlist)
#['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 
#'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
# 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 
#'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 
#'yield']

3.表达式

  • 用运算符链接各种类型数据的式子就是表达式
  • 表达式必须有运算结果,结果赋值给一个变量。

4. 运算符

算术运算符

操作符名称示例
+1 + 1
-2 - 1
*3 * 4
/3 / 4
//整除(地板除)3 // 4
%取余3 % 4
**2 ** 3

【例子】

print(1 + 1)  # 2
print(2 - 1)  # 1
print(3 * 4)  # 12
print(3 / 4)  # 0.75
print(3 // 4)  # 0
print(3 % 4)  # 3
print(2 ** 3)  # 8

比较运算符
bool型

  • 数值的比较:按值的大小
  • 字符串的比较:按ASCII码比较
操作符名称示例
>大于2 > 1
>=大于等于2 >= 4
<小于1 < 2
<=小于等于5 <= 2
==等于3 == 4
!=不等于3 != 5

【例子】

print(2 > 1)  # True
print(2 == 4)  # False
print(1 < 2)  # True
print(3 <4< 3)  # False(在C语言中永远为真,3<4为真(1),1永远小于3)
print('abc' <'xyz')  # True

逻辑运算符
bool型

操作符名称示例
and(3 > 2) and (3 < 5)
or(1 > 3) or (9 < 2)
notnot (2 > 1)

【例子】

print((3 > 2) and (3 < 5))  # True
print((1 > 3) or (9 < 2))  # False
print(not (2 > 1))  # False

字符运算符

  • 原始字符串操作符(r/R)
    – 用于一些不希望转义字符起作用的地方 (后面的字符串都按字面意思解释)
  • 所有的字符串都是Unicode字符串:
    – python2.x中需要转换成Unicode字符串
f = open('C:\Users\cey\Desktop\test.py','w')
# File "<ipython-input-14-213f89b1969b>", line 1    f=open('C:\Users\cey\Desktop\test.py','w')
#           ^
#     SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
f = open(r'C:\Users\cey\Desktop\test.py','w')
f = open('C:\\Users\\cey\\Desktop\\test.py','w')#也可以用转意字符如一个\可以用\\来转意
print u'Hello\nWorld'
#hello
#world

位运算符

操作符名称示例
~按位取反~4
&按位与4 & 5
|按位或4 | 5
^按位异或4 ^ 5
<<左移4 << 2
>>右移4 >> 2

【例子】有关二进制的运算,参见“位运算”部分的讲解。

print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1

三元运算符
【例子】

x, y = 4, 5
if x < y:
    small = x
else:
    small = y
print(small)  # 4

有了这个三元操作符的条件表达式,你可以使用一条语句来完成以上的条件判断和赋值操作。
【例子】

x, y = 4, 5
small = x if x < y else y
print(small)  # 4

其他运算符

操作符名称示例
in存在'A' in ['A', 'B', 'C']
not in不存在'h' not in ['A', 'B', 'C']
is"hello" is "hello"
is not不是"hello" is not "hello"

【例子】

letters = ['A', 'B', 'C']
if 'A' in letters:
    print('A' + ' exists')
if 'h' not in letters:
    print('h' + ' not exists')
# A exists
# h not exists

【例子】比较的两个变量均指向不可变类型。

a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False

【例子】比较的两个变量均指向可变类型。

a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False

注意:

  • is, is not 对比的是两个变量的内存地址
  • ==, != 对比的是两个变量的值
  • 比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
  • 对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
    运算符的优先级
  • 一元运算符优于二元运算符。例如3 ** -2等价于3 ** (-2)
  • 先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7等价于 1 << (3 + 2)) & 7
  • 逻辑运算最后结合。例如3 < 4 and 4 < 5等价于(3 < 4) and (4 < 5)
    【例子】
print(-3 ** 2)  # -9
print(3 ** -2)  # 0.1111111111111111
print(1 << 3 + 2 & 7)  # 0
print(-3 * 2 + 5 / -2 - 4)  # -12.5
print(3 < 4 and 4 < 5)  # True

5.赋值(=)

  • 变量第一次赋值,同时获得类型和 “值”
    -Python是动态的强类型语言
    -不需要显示声明,根据 “值” 来确定类型
    -以“引用”的方式来实现赋值
    [例子]
pi = 3.1415
PI = 'one word'
print(pi) #3.1415
print(PI) #one word

Python中每个对象被创建的时候都会获得一个身份id(可以用id函数查看),同时会伴随一个引用计数器。对于下面的例子虽然两个3.5相同,但他们有各自的内存空间

[例子]

x = 3.5
y = x
y is x #Ture
z = 3.5
z is x #False
id(x) #2366969038144
id(y)#2366969038144
id(z)#2366969038216

注意:对于[-5,256]范围内的相同小整数和部分仅包含数字字母和下划线的字面常量字符串会被驻留,也就是分配同一个内存空间,因为这些对象比较常用。(这种高效的存储方式可以优化程序的运行速度)
另外,python标准规定如果在同一个语句块中相同的不可变对象,不另外再分配空间,例如x和y在同一个函数中,属于同一个语句块,如果给他们都赋值为一个大整数(eg:1000,3.5),则他们的内存空间相同。

p = 256
q = 256
p is q #True

增量赋值

增量赋值操作符:+=,-=,/=,%=,**=,<<=, >>=, &=, ^=, |=

即时把一些运算符号和赋值符号放在一起

m = 18
m %=5
m # 3
# m %=5 即 m = m % 5

链式赋值

PI = 3.1415
pi = PI = PI*2
PI#6.283
pi#6.283

多重赋值

等号两边都以元组的方式出现

PI,r = 3.1415,3
PI,r#(3.1415, 3)

语句

  • 完整执行一个任务的一行逻辑代码
    -赋值语句完成了赋值
    -print速出语句完成输出
PI = 3.14159
r = 2
c_circ = 2*PI*r
print("The circle'circum is",c_circ)
#The circle'circum is 12.56636

语句和表达式的区别

  • 语句:完成一个任务,如:打印一个文件
  • 表达式:任务中的一个具体组成部分,如:这份文件的具体内容。

数据类型

整型

-机器字长为32位,标准整型范围: − 2 31 -2^{31} 231~ 2 31 − 1 2^{31}-1 2311
-机器字长为64位,标准整型范围: − 2 63 -2^{63} 263~ 2 63 − 1 2^{63}-1 2631

  • 长整型范围远超c语言等其他语言,其跟机器支持的内存大小有关。因此可以轻松的表达很长的整型,不用担心溢出问题。
  • 在python2.2以后,整型与长整型没有严格的区分。
布尔型
  • 整型的子类
  • 两个值:True,False
  • 本质上是用整型的1,0分别存储
x = True
type(x)#bool
int(x)#1
y = False
int(y)#0
浮点型
  • 即数学中的实数
  • 可以类似科学计数法表示
8.94e-2#0.0894
type(8.94e-2)#float
复数型
  • j= − 1 \sqrt{-1} 1 , 则 j是虚数
  • 实数+虚数,就是复数
  • 虚数部分必须有 j
type(2.4+5.6j)#complex
  • 复数可以分离实部和虚部
    -复数.real
    -复数.imag
  • 复数的共轭
    -复数.cojugate
x = 2.4+5.6j
x.real#2.4
x.imag#5.6
x.conjugate#(2.4-5.6j)

`方式进行转换为字符串输出;

  • 关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
  • 关键字参数end是输出结束时的字符,默认是换行符\n
  • 关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
  • 关键字参数flush是立即把内容输出到流文件,不作缓存。
    【例子】没有参数时,每次输出后都会换行。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:
    print(item)
# This is printed without 'end'and 'sep'.
# apple
# mango
# carrot
# banana

【例子】每次输出结束都用end设置的参数&结尾,并没有默认换行。

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
    print(item, end='&')
print('hello world')
# This is printed with 'end='&''.
# apple&mango&carrot&banana&hello world

【例子】item值与'another string'两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
    print(item, 'another string', sep='&')
# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string

参考文献

  • https://www.runoob.com/python3/python3-tutorial.html
  • https://www.bilibili.com/video/av4050443
  • https://mp.weixin.qq.com/s/DZ589xEbOQ2QLtiq8mP1qQ
  • https://www.cnblogs.com/OliverQin/p/7781019.html

练习题

  1. 怎样对python中的代码进行注释?
  2. python有哪些运算符,这些运算符的优先级是怎样的?
  3. python 中 is, is not==, != 的区别是什么?
  4. python 中包含哪些数据类型?这些数据类型之间如何转换?
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值