Alibaba Cloud Python Training Camp (day1)


Introduction

Python is a general-purpose programming language, which has a wide range of applications in the fields of scientific computing and machine learning. If we plan to use Python to perform machine learning, then a basic understanding of Python is essential. This Python introductory series experience is carefully prepared for such beginners.


One, variables, operators and data types

1. Notes

In Python, # represents a comment, which applies to the entire line.

# 这是一个注释
print("Hello world")

# Hello world
Hello world

'''''' or """ """ means interval comment, all content between triple quotation marks is commented

2. Operator

Arithmetic operators:

Operator name Example result
+ plus 1+1 2
- Less 8-7 1
* Multiply 6*5 30
/ except 3/4 0.75
// Divide 3//4 0
% Take the remainder 6%4 2
** power 2**4 16

Comparison operator:

Operator name Example result
> more than the 2>1 True
<= name 1<=1 True
< name 2<1 False
<= name 2<=9 True
== name 2==0 False
!= name 3!= 4 True

Logical Operators:

Operator name Example result
and versus (3>2)and(4<5) True
or or (3<2)and(4>5) False
not non- not(4==6) False

Bit operator:

Operator name Example result
~ Bitwise negation ~4 -5
& Bitwise and 4&5 4
^ Bitwise XOR 4^5 1
<< Shift left 4<<2 16
>> Shift right 4>>2 1

Other operators:

Operator name Example result
in exist ‘A’ in [‘A’, ‘B’, ‘C’] A exists
not in does not exist ‘h’ not in [‘A’, ‘B’, ‘C’] h not exists
is Yes “hello” is “hello” True
not is Is not “hello” is not “hello” False

Note:
(1) is, is not compares the memory addresses of two variables
(2) = =, != compares the values ​​of the two variables
(3) compares the two variables, pointing to immutable addresses Type (str, etc.), then is, is not and ==,! = Is completely equivalent.
(4) The two compared variables point to the variable address type (list, dict, tuple, etc.), there is a difference between the two.

The precedence of operators:
(1) Unary operators are better than binary operators. For example, 3 ** -2 is equivalent to 3 ** (-2).
(2) Arithmetic operation first, shift operation second, bit operation last. For example, 1 << 3 + 2 & 7 is equivalent to (1 << (3 + 2)) & 7.
(3) The logic operation is finally combined. For example, 3 <4 and 4 <5 is equivalent to (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

3. Variables and assignment

1. Before using a variable, you need to assign a value to it.
2. The variable name can include letters, numbers, and underscores, but the variable name cannot start with a number.
3. Python variable names are case sensitive, foo != Foo.

4. Data Type and Conversion

Types of name Example
int Integer <class'int'> 10
float Floating point <class'float'> 11.11
bool Boolean <class'bool'> True,Flase

Integer type: In
python, use the type method to view the type, and use the bin method to view the corresponding binary number

a = 5
print( type(a))
print(bin(a))

<class ‘int’>
0b101


Floating point:

print(1., type(1.))
# 1.0 <class 'float'>

a = 0.00000023
b = 2.3e-7
print(a)  # 2.3e-07
print(b)  # 2.3e-07

有时候我们想保留浮点型的小数点后 n 位。可以用 decimal 包里的 Decimal 对象和 getcontext() 方法来实现。

小贴士:Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal) 来看其属性和方法。

例子:使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)

# 0.3333

布尔型:
布尔 (boolean) 型变量只能取两个值,True 和 False。当把布尔型变量用在数字运算中,用 1 和 0 代表 True 和 False。

print(True + True)  # 2
print(True + False)  # 1
print(True * False)  # 0

除了直接给变量赋值 True 和 False,还可以用 bool(X) 来创建变量,其中 X 可以是
(1).基本类型:整型、浮点型、布尔型
(2).容器类型:字符串、元组、列表、字典和集合

例子:bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是 False。

print(type(''), bool(''), bool('python'))
# <class 'str'> False True

print(type(()), bool(()), bool((10,)))
# <class 'tuple'> False True

确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。
(1)对于数值变量,0, 0.0 都可认为是空的。
(2)对于容器变量,里面没元素就是空的。获取类型信息获取类型信息 type(object)


类型判断:
如果要判断两个类型是否相同推荐使用 isinstance()。

类型转换:
转换为整型 int(x, base=10)
转换为字符串 str(object=’’)
转换为浮点型 float(x)


5. print()函数

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

(1) 将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有(2) 非关键字参数都按str()方式进行转换为字符串输出;
(3) 关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
(3) 关键字参数end是输出结束时的字符,默认是换行符\n;
(4) 关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
(5) 关键字参数flush是立即把内容输出到流文件,不作缓存。

二、位运算

1.原码、反码和不补码

二进制有三种不同的表示形式:原码、反码和补码,计算机内部使用补码来表示。
(1) 原码:就是其二进制表示(注意,有一位符号位)。

00 00 00 11 -> 
310 00 00 11 -> -3

(2) 反码:正数的反码就是原码,负数的反码是符号位不变,其余位取反(对应正数按位取反)。

00 00 00 11 -> 
311 11 11 00 -> -3

(3) 补码:正数的补码就是原码,负数的补码是反码+1。

00 00 00 11 -> 3
11 11 11 01 -> -3

符号位:最高位为符号位,0表示正数,1表示负数。在位运算中符号位也参与运算。

2.按位运算

(1) 按位非操作~:

 ~1 = 0
 ~0 = 1

~ 把num的补码中的 0 和 1 全部取反(0 变为 1,1 变为 0)有符号整数的符号位在 ~ 运算中同样会取反。

(2) 按位与操作 &:

1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0

只有两个对应位都为 1 时才为 1

(3) 按位或操作 |

1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0

只要两个对应位中有一个 1 时就为 1

(4) 按位异或操作 ^:

1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0

只有两个对应位不同时才为 1
异或操作的性质:满足交换律和结合律

(5) 按位左移操作 <<:

num << i 将num的二进制表示向左移动i位所得的值。

00 00 10 11 -> 11
11 << 3
---
01 01 10 00 -> 88 

(6) 按位右移操作 >>:

num >> i 将num的二进制表示向右移动i位所得的值。

00 00 10 11 -> 11
11 >> 2
---
00 00 00 10 -> 2 

3.用位运算实现快速计算

(1) 通过 <<,>> 快速计算2的倍数问题。

n << 1 -> 计算 n*2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n*(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n

(2) 通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。

a ^= b
b ^= a
a ^= b

(3) 通过 a & (-a) 快速获取a的最后为 1 位置的整数。

00 00 01 01 -> 5
&
11 11 10 11 -> -5
---
00 00 00 01 -> 1

00 00 11 10 -> 14
&
11 11 00 10 -> -14
---
00 00 00 10 -> 2

4.利用位运算实现整数集合

一个数的二进制表示可以看作是一个集合(0 表示不在集合中,1 表示在集合中)。

比如集合 {1, 3, 4, 8},可以表示成 01 00 01 10 10 而对应的位运算也就可以看作是对集合进行的操作。

元素与集合的操作:a | (1<<i) -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i) -> 判断 i 是否属于该集合(零不属于,非零属于)

集合之间的操作:a 补 -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)

注意:整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。

例子:

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        string s1 = Convert.ToString(-3, 2);
        Console.WriteLine(s1); 
        // 11111111111111111111111111111101
        
        string s2 = Convert.ToString(-3, 16);
        Console.WriteLine(s2); 
        // fffffffd
    }
}

在根据bin()的输出,可以看出:
(1)Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号
(2)Python中的整型是补码形式存储的。
(3)Python中整型是不限制长度的不会超范围溢出。

所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。

Guess you like

Origin blog.csdn.net/qq_44250569/article/details/108713087