Python新手入门-5

简介: Python新手入门-5

5. 使用Python运算符

1. 使用操作运算符。

操作符

名称

示例

+

1+1

-

2-1

*

3*4

/

3/4

//

整除(地板除)

3//4

%

取余

3%4

**

2**3

执行如下Python语句。

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

执行如下Python语句。

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)

执行如下Python语句。

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

4. 位运算符。

操作符

名称

示例

~

按位取反

~4

&

按位与

4&5

|

按位或

4|5

^

按位异或

4^5

<<

左移

4<<2

>>

右移

4>>2

执行如下Python语句。

print(bin(4))
print(bin(5))
print(bin(~4),~4)
print(bin(4&5),4&5)
print(bin(4|5),4|5)
print(bin(4^5),4^5)
print(bin(4<<2),4<<2)
print(bin(4>>2),4>>2)

5. 三元运算符。

三元运算符的语法如下。

exp1 if condition else exp2

说明:

condition是判断条件,exp1和exp2是两个表达式。如果condition成立(结果为真),就执行exp1,并把exp1的结果作为整个表达式的结果;如果condition不成立(结果为假),就执行exp2,并把exp2的结果作为整个表达式的结果。

执行如下Python语句。

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

6. 使用in和not in运算符。

操作符

名称

示例

in

存在

A' in ['A','B','C']

not in

不存在

'h' not in ['A','B','C']

执行如下Python语句。

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

7. is和is not运算符。

操作符

名称

示例

is

"hello" is "hello"

is not

不是

"hello" is not "hello"

说明:

  • is、is not对比的是两个变量的内存地址。
  • ==、!=对比的是两个变量的值。
  • 比较的两个变量,指向的都是地址不可变的类型(str等),那么is、is not和==、!=是完全等价的。
  • 比较的两个变量,指向的是地址可变的类型(list、dict等),那么is、is not和==、!=不是等价的。

a. 比较的两个变量均指向不可变类型。

执行如下Python语句。

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

b. 比较的两个变量均指向可变类型。

执行如下Python语句。

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

8. 执行如下Python语句,退出Python。

exit()
目录
相关文章
|
Python
Python新手入门3
Python新手入门3
162 0
Python新手入门3
|
Python
Python新手入门2
Python新手入门2
79 0
Python新手入门2
|
开发工具 Python
Python新手入门-11
Python新手入门-11
120 0
Python新手入门-11
|
开发工具 Python
Python新手入门-10
Python新手入门-10
78 0
Python新手入门-10
|
开发工具 Python
Python新手入门-9
Python新手入门-9
80 0
Python新手入门-9
|
开发工具 索引 Python
Python新手入门-8
Python新手入门-8
104 0
Python新手入门-8
|
开发工具 Python
Python新手入门-7
Python新手入门-7
108 0
Python新手入门-7
|
弹性计算 人工智能 Linux
Python新手入门1
Python新手入门1
84 0
|
弹性计算 人工智能 Linux
Python新手入门-1
Python新手入门-1
90 0