目录
python 基本语法学习(一)
一.变量、运算符与数据类型
1.注释
(1)在 Python 中,#
表示注释,作用于整行。
# 这是一个注释
print("Hello world")
# Hello world
(2 )""" """
表示区间注释,在三引号之间的所有内容被注释
'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
print("Hello china")
# Hello china
"""
这是多行注释,用三个双引号
这是多行注释,用三个双引号
这是多行注释,用三个双引号
"""
print("hello china")
# hello china
2.运算符
(1)算术运算符
操作符 | 名称 | 示例 |
+ | 加 | 1+1 |
- | 减 | 6-5 |
* | 乘 | 5*5 |
/ | 除 | 3/4 |
// | 整除(地板除) | 6//6 |
% | 取余 | 3%2 |
** | 幂 | 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
(2)比较运算符
操作符 | 名称 | 示例 |
> | 大于 | 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(5 <= 2) # False
print(3 == 4) # False
print(3 != 5) # True
(3)逻辑运算符
操作符 | 名称 | 示例 |
and | 与 | (3 > 2) and (3 < 5) |
or | 或 | (1 > 3) or (9 < 2) |
not | 非 | not (2 > 1) |
print((3 > 2) and (3 < 5)) # True
print((1 > 3) or (9 < 2)) # False
print(not (2 > 1)) # False
(4)位运算符
操作符 | 名称 | 示例 |
~ | 按位取反 | ~4 |
& | 按位与 | 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
(5)三元运算符
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
(6)其他运算符
操作符 | 名称 | 示例 |
in | 存在 | 'A' in ['A','B','C'] |
not in | 不存在 | 'h' not in ['A','B','C'] |
is | 是 | "hello" is "hello" |
not is | 不是 | "hello" is not "hello" |
例1
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
例2 比较的两个变量均指向不可变类型
a = "hello"
b = "hello"
print(a is b, a == b) # True True
print(a is not b, a != b) # False False
例3 比较的两个变量均指向可变类型
a = ["hello"]
b = ["hello"]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False
注:1.is, is not 对比的是两个变量的内存地址.
2.==, != 对比的是两个变量的值.
3.比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的.
4.对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的.
3.变量和赋值
- 在使用变量之前,需要对其先赋值。
- 变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
- Python 变量名是大小写敏感的,foo != Foo.
例1 输出加法运算
first = 2
second = 3
third = first + second
print(third) # 5
例2 连接字符串并输出
myTeacher = "欢迎来到python的世界"
yourTeacher = "从入门到放弃"
ourTeacher = myTeacher + ',' + yourTeacher
print(ourTeacher) # 欢迎来到python的世界,从入门到放弃
例3 尝试用pop()方法来随机移除一个元素
# 运行一下就好啦
set_1 = {"欢迎", "学习","Python"}
print(set_1.pop())
4.数据类型与转换
类型 | 名称 | 示例 |
int | 整型<class 'int'> | -876,10 |
float | 浮点型<class 'float'> | 3.149,11.11 |
bool | 布尔型<class 'bool'> | True, False |
例1 通过 print()
可看出 a
的值,以及类 (class) 是int
。
a = 1031
print(a, type(a))
# 1031 <class 'int'>
Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)。dir(模块)用于返回模块的属性列表。
b = dir(int)
print(b)
# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',
# '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__',
# '__float__', '__floor__', '__floordiv__', '__format__', '__ge__',
# '__getattribute__', '__getnewargs__', '__gt__', '__hash__',
# '__index__', '__init__', '__init_subclass__', '__int__', '__invert__',
# '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__',
# '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__',
# '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
# '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
# '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
# '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
# '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__',
# 'bit_length', 'conjugate', 'denominator'
对它们有个大概印象就可以了,具体怎么用,需要哪些参数 (argument),还需要查文档。
例2 看个bit_length()
的例子
a = 1031
print(bin(a)) # 0b10000000111
print(a.bit_length()) # 11
有时候我们想保留浮点型的小数点后 n
位。可以用 decimal
包里的 Decimal
对象和 getcontext()
方法来实现。
首先要引用包,Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal)
来看其属性和方法。
import decimal
from decimal import Decimal
例3 getcontext()
显示了 Decimal
对象的默认精度值是 28 位 (prec=28
)
a = decimal.getcontext()
print(a)
# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
# capitals=1, clamp=0, flags=[],
# traps=[InvalidOperation, DivisionByZero, Overflow])
b = Decimal(1) / Decimal(3)
print(b)
# 0.3333333333333333333333333333
#小数点后面默认是28位
例4 使 1/3 保留 4 位,用 getcontext().prec
来调整精度
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)
# 0.3333
#设置精确度为4
布尔 (boolean) 型变量只能取两个值,True
和 False
。当把布尔型变量用在数字运算中,用 1
和 0
代表 True
和 False。
例5
print(True + True) # 2
print(True + False) # 1
print(True * False) # 0
除了直接给变量赋值 True
和 False
,还可以用 bool(X)
来创建变量,其中 X
可以是
- 基本类型:整型、浮点型、布尔型
- 容器类型:字符串、元组、列表、字典和集合
例6 bool
作用在基本类型变量:X
只要不是整型 0
、浮点型 0.0
,bool(X)
就是 True
,其余就是 False
。
print(type(0), bool(0), bool(1))
# <class 'int'> False True
print(type(10.31), bool(0.00), bool(10.31))
# <class 'float'> False True
print(type(True), bool(False), bool(True))
# <class 'bool'> False True
例7 bool
作用在容器类型变量:X
只要不是空的变量,bool(X)
就是 True
,其余就是 False
。
print(type(''), bool(''), bool('python'))
# <class 'str'> False True
print(type(()), bool(()), bool((10,)))
# <class 'tuple'> False True
print(type([]), bool([]), bool([1, 2]))
# <class 'list'> False True
print(type({}), bool({}), bool({'a': 1, 'b': 2}))
# <class 'dict'> False True
print(type(set()), bool(set()), bool({1, 2}))
# <class 'set'> False True
确定bool(X)
的值是 True
还是 False
,就看 X
是不是空,空的话就是 False
,不空的话就是 True
。
- 对于数值变量,
0
,0.0
都可认为是空的。 - 对于容器变量,里面没元素就是空的。
获取类型信息
- 获取类型信息
type(object)
print(isinstance(1, int)) # True
print(isinstance(5.2, float)) # True
print(isinstance(True, bool)) # True
print(isinstance('5.2', str)) # True
注:
type()
不会认为子类是一种父类类型,不考虑继承关系。isinstance()
会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()
。
类型转换
- 转换为整型
int(x, base=10)
- 转换为字符串
str(object='')
- 转换为浮点型
float(x)
例8
print(int('520')) # 520
print(int(520.52)) # 520
print(float('520.52')) # 520.52
print(float(520)) # 520.0
print(str(10 + 10)) # 20
print(str(10.1 + 5.2)) # 15.3
5.print()函数
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- 将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按
str()
方式进行转换为字符串输出; - 关键字参数
sep
是实现分隔符,比如多个参数输出时想要输出中间的分隔字符; - 关键字参数
end
是输出结束时的字符,默认是换行符\n
; - 关键字参数
file
是定义流输出的文件,可以是标准的系统输出sys.stdout
,也可以重定义为别的文件; - 关键字参数
flush
是立即把内容输出到流文件,不作缓存。
例9 没有参数时,每次输出后都会换行。
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
例10 每次输出结束都用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
例11 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
4. 条件语句
1.if语句
if expression:
expr_true_suite
- if 语句的
expr_true_suite
代码块只有当条件表达式expression
结果为真时才执行,否则将继续执行紧跟在该代码块后面的语句。 - 单个 if 语句中的
expression
条件表达式可以通过布尔操作符and
,or
和not
实现多重条件判断。
例1
if 2 > 1 and not 2 > 3:
print('Correct Judgement!')
# Correct Judgement!
2.if-else语句
if expression:
expr_true_suite
else:
expr_false_suite
- Python 提供与 if 搭配使用的 else,如果 if 语句的条件表达式结果布尔值为假,那么程序将执行 else 语句后的代码。
例2
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")
if
语句支持嵌套,即在一个if
语句中嵌入另一个if
语句,从而构成不同层次的选择结构。
例3 Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意else
的悬挂问题。
hi = 6
if hi > 2:
if hi > 7:
print('好棒!好棒!')
else:
print('切~')
# 无输出
例4
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > 8:
print("大了,大了")
else:
if guess == 8:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("小了,小了")
print("游戏结束,不玩儿啦!")
3. if-elif-else语句
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
elif expressionN:
exprN_true_suite
else:
expr_false_suite
- elif 语句即为 else if,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。
temp = input('请输入成绩:')
source = int(temp)
if 100 >= source >= 90:
print('A')
elif 90 > source >= 80:
print('B')
elif 80 > source >= 60:
print('C')
elif 60 > source >= 0:
print('D')
else:
print('输入错误!')