The python basic arithmetic operations and data types

A coding standard .python

1. semicolon: Do not add a semicolon end of the line, and do not use semicolons two commands on the same line

2. Line length: Under normal circumstances each line not more than 80 characters

3. brackets: Ningquewulan parentheses

4. Indentation: 4 spaces to indent the code

The blank lines: two blank spaces defined between the top, a blank line between the method definition

6. statement: through each sentence should be a separate line

7. Try to avoid spaces in the file name and Chinese

Second, the basic syntax of python

python syntax is relatively simple, indented way to write code something like this:

# print absolute value of an integer:
a = 100
if a >= 0:
    print(a)
else:
    print(-a)

Where # is the beginning of the statement is a comment, the comment is for programmers to see, the interpreter will ignore the comment. Every other row is a statement to the statements: colon end is indented statement block.

By convention Always use indented four spaces (either space or Tab key can be), in a text editor, set the Tab automatically converted into four spaces to

Note: Python program is case sensitive

Third, the identifier

What is the identifier? Plainly it is a string

The rules for identifiers:

1. Only letters, numbers, underscores

2. The beginning is not digital

3. can not be a python keyword

For example: def False True and break class del etc.

4. The case-sensitive

5. Take the name of justice to do see the name to know

effect:

To variables, functions, etc. named

Four, python data types and variables

(A) Data Types

Why are there different types of data

The computer is used to make mathematical calculations of the machine, so it can handle a variety of values, but the computer can handle much more than the value, it can handle a variety of data, text, graphics, audio, video, etc., different to define the data of different data types.

python data types are divided into several?

1.Number (Digital)
      ​       a.整数 :python可以处理任意大小的整数,当然包括负整数,在程序的表示方法和数学上的写法是一模一样的,例如:1, 100, -10等

      ​       b.浮点数:浮点数又称小数,之所以称之为浮点数,是因为按照科学计数法表示的的时候,一个浮点数的位置是可变的,比如1.23x10^5 与 12.3x10^4是相等的。[在python中浮点数的表示会有一定的误差,这个误差的原因是实数的无限精度跟计算机的有限内存之间的矛盾]

      注意:整数与浮点数在计算机内存的存储方式不同,整数运输是精确的,而浮点数运算则可能会有四舍五入的误差。

      ​       c.复数:复数由实数部分和虚数部分组成,可以用a+bj或者complex(a,b)的形式表示,复数的实部a和虚部b都是浮点型。     
2.String (string)

String is a single or double quotes any text, such as "abc", 'xy', etc. Please note '' or '' is just a representation of itself, is not part of the string.

a. If the internal string contains a single quote and double quotes how to do?

print('I\'m \"ok\"')

A string representation of the contents are:

I'm "ok"

Note: The escape character \ can escape a lot of character, such as \ n for newline, \ t for a tab character \ itself needs to escape, so the character is represented \\ \ etc

>>>print('I\'m ok.')
I'm ok.
>>>print('I\'m learning\n python.')
I'm leanring
Python.
>>> print('\\\n\\')
\
\

However, if there are many strings string needs to be escaped, we need to add much, for simplicity, but also allows Python r "" inside a string representing the default is not escape.

>>> print('\\\t\\')
\   \
>>>print(r'\\\t\\')
\\\t\\

If the internal string a lot of line breaks, using \ n write one line is not good reading, in order to simplify, python allows '' ... '' is a multi-line format:

>>> print('''line1
    line2
    line3''')
line1
line2
line3
3.Boolean (Boolean value)

Only Boolean value True, False two kinds of value, can be directly used in python True, False Boolean value indicating [] attention to the case, can also be calculated by Boolean operators:

>>> True
True
>>> 3 > 2
True
4.None (null)

Null value is a special value in the python, represented by None, 0 is not None, and None is a special null value.

5.list (list)

Python built-in data type is a list: list. list is an ordered set, which you can add and remove elements at any time

>>> list1 = ["张三", "王二", "李四"]
>>> type(list1)
<class 'list'>
6.tuple (tuple)

Another called an ordered list of tuples: tuple. tuple and the list is very similar, but the tuple can not be changed once initialized

>>> tuple1 = ("张三", "王二", "李四")
>>> type(tuple1)
<class 'tuple'>
7.dict (dictionary)

Python built-in dictionary: dict support, dict full name of the dictionary, in other languages ​​also called map, using a key - value (key-value) memory, has a fast search speed.

>>> dict1 = {'lisi': 89, 'lili':90}
>>> type(dict1)
<class 'dict'>
8.set (collection)

Similar dict and set, a set key is set, but not stored value. Since the key can not be repeated, so that, in the set, no duplicate key.

>>> set1 = {"lisi", "wanger"}
>>> type(set1)
<class 'set'>
(B) variable

Variable concept and substantially junior algebraic equation variables is the same, but in a computer program, the variables may be not only numbers, can also be any data type.

1. Overview: The name of the program is operable to store, can be changed during operation of the data, the type of each variable are specific

Action: the different types of data stored in memory

2. Variable definitions:

Variable name = initial value

age = 18

NOTE: The reason is given as initial value to determine the type of the variable

age = 18
print('age =', age)
#查看变量的类型
print(type(age))
#查看变量的地址
print(id(age))

3. To delete a variable:

del variable name

Note: Variables can not delete the references

age = 18
#删除age变量
del age
#打印age的值
print('age =', age)

Note: In Python, the equal sign assignment symbol, any data type can be assigned to a variable, the same evaluation may be repeated a variable, and can be different types of variables. This in itself is not fixed like the type of the language is referred to as dynamic language .

Of course, you also can be understood, the type of a variable is assigned depends on the type of value.

a = 123 #a是整数
print(a)
print(type(a))
a = 'abc' #a变为字符串
print(a)
print(type(a))
(C) constants:

It can not be changed during the run data

#常见的常量
123
'abc'

Five, Number (digital)

1. The conversion between the digital type
> int(x) :将x转换为一个整数

> float(x) :将x转换为一个浮点数
#浮点数转为int
print(int(1.9))
# int转为浮点数
print(float(1))
#字符串转为int
print(int('123'))
#字符串转为float
print(float('12.3'))
#注意:如果有其他无用字符会报错,比如:
print(int('abc'))
#只有正负号才有意义
print(int('+123'))
print(int('-123'))
2. Mathematical Functions

abs (x): Returns the absolute value

(X> y) - (x <y): size comparison, the value of n x> y, x value is negative

#返回数字的绝对值
num1 = -10
num2 = abs(num1)
print(num2)

#比较两个数的大小
num3 = 100
num4 = 8
print((num3 > num4)-(num3 < num4))

#返回给定参数的最大值
print(max(1, 2, 3, 45, 34, 12))

#返回给定参数的最小值
print(min(12354))

#求x的y次方  2^5
print(pow(2, 5))

#round(x[,n])返回浮点数x的四舍五入的值,如果给出n值,则代表舍入到小数点后n位
#默认保留整数
print(round(2.1234))
print(round(2.13334, 3))
Use 3.math module

The math module Import

math.ceil (x): Returns the value of x rounded up

math.floor (x): Returns the value of x rounded down

math.modf (x): Returns the integer x and fractional parts, the two parts of the sign of the value the same as x, a floating point number represents an integer part.

math.sqrt (x): Anti-digit return the square root of x, the return type is real [float]

import math

#向上取整
print(math.ceil(18.1))
print(math.ceil(18.8))

#向下取整
print(math.floor(18.1))
print(math.floor(18.9))

#返回整数部分与小数部分
print(math.modf(22.123))

#开方
print(math.sqrt(16))
4. The random number function

Import module random

random.choice ([1,2,3,4]): [returns a random element selected from an element in the specified sequence]

random.randrange (n): From 0 ~ n-1 between a random number

random.random (): random number between [0, 1), floating-point numbers

l1 = [1, 2, 4, 5]

random.shuffle (l1): all the elements in the sequence will be randomly arranged

random.uniform (m, n): randomly generating a [m, n] between the float

import random

nums = range(10)
# range([start,] stop[, step])
# range()函数返回一个可迭代对象
# start:计数从start开始,默认从0开始
# stop:计数到stop结束,但不包括stop
# step: 步长,默认为1
list(nums)
# 使用list可以把可迭代对象转为一个列表,返回的类型为列表
#随机数
print(random.choice([1,3,4,5]))
print(random.choice(range(5)))
print(random.choice("hello"))

#产生一个1~100之间的随机数
r1 = random.choice(range(100))+1
print(r1)

#从指定范围内,按指定的基数递增的集合中选取一个随机数
#random.randrange([start,]stop[, step])
#start:指定范围的开始值,包含在范围内,默认是0
#stop:指定范围结束值,不包含在范围内
#step:指定的递增基数,默认是1
print(random.randrang(1, 100, 2))

#从0~99选取一个随机数
print(random.randrang(100))

#随机产生[0,1)之间的数(浮点数)
print(random.random())

#随机产生一个实数,在[3,9]范围内
print(random.uniform(3, 9))

list = [1, 2, 3, 23, 21]
#将序列的所有元素随机排序
random.shuffle(list)
print(list)
5. trigonometric functions

Need to import math module

Six, arithmetic operators and expressions

Arithmetic Operators
 假设变量 a = 10, b = 20
+  :加 两个对象相加   例如 a + b = 30
-  :减 标识负数/一个数减去另一个数  a - b = -10
*  :乘 两个数相乘/返回一个被重复若干次的字符串 a*b=200
/  : 除 b除以a  b/a = 2
%  : 取模 返回除法的余数  b%a = 0
** :幂,返回x的y次幂  a**b=10^20
// : 取整除返回商的整数部分  9//2=4, 9.0//2.0=4.0
Arithmetic expressions
3+2  3-1  8**9  5%3
功能:进行相关符号的数学运算,不会改变变量的值
值:相关的数学运算的结果

Seven, comparison operators

== equal, whether the comparison is equal, the return boolean values

>>> a = 10
>>> b = 20
>>> print(a == b)
False

! = Not equal, the comparison objects are not equal

>>> a = 10
>>> b = 20
>>> print(a != b)
True

Greater than, x> y, if x is greater than y to return

>>> a = 10
>>> b = 20
>>> print(a > b)
False

<Less than, x <y, x is less than y return

>>> a = 10
>>> b = 20
>>> print(a < b)
True

'> =' Greater than or equal, x> = y, x is greater than or equal to y return

>>> a = 10
>>> b = 20
>>> print(a >= b)
False

<= Less than or equal, x <= y, x is less than or equal to y return

>>> a = 10
>>> b = 20
>>> print(a <= b)
True

Eight, assignment operator and the assignment operator expression

Assignment operator =
assignment expression
format: variable = expression

Function: Compute the value of "expression" of the right of the equal sign, and assigned to the left side of the equal sign variable
variable after the end of the assignment: Value

num1 = 10
num2 = num1 + 2

Composite Operators

+=  加法赋值运算符     a += b   a = a + b
-=  减法赋值运算符     a -= b   a = a - b
*=  乘法赋值运算符     a *= b   a = a * b
/=  除法赋值运算符     a /= b   a = a / b
%=  取模赋值运算符     a %= b   a = a % b
**= 幂赋值运算符       a **= b  a = a ** b
//= 取整除赋值运算符    a //= b  a = a // b

Nine, logical operators

and operations are the operations, only if all are True, and result of the operation is True :

>>> True and True
True
>>> True and False
False
>>> 5>3 and 3>1
True

OR operation or operation is, as long as one is True, the result is True or operator

>>>True or True
True
>>>True or False
True
>>>False or False
False

not operator is non-operational, it is a unary operator, into the True False, False True into

>>> not True
False
>>> not False
True
>>> not 1>2
True

Short circuit principle

Expression 1 and Expression 2 and Expression 3 1 ... If the expression is false, the entire expression is false, the expression that is not necessary to calculate the

Expression 1 or Expression 2 or Expression 3 1 ... If the expression is true, then the entire expression is true, the value of the expression is not necessary back calculated

X. bitwise operator

我们进行位运算的时候,我们需要把数字转换为二进制数来进行计算
&   按位与
|   按位或
^   按位异或
~  按位取反
<<  左移
>>  右移

[&] 1. operational

Operations involved in two values, if the corresponding two bits are 1, then the 1-bit result is 0 otherwise

3 & 2 = 2

0 1 1
0 1 0
------
0 1 0

2. Press or position [|]

As long as the corresponding two bits, there is a 1, the result is a 1 bit is

3 | 2 = 3

0 1 1
0 1 0
-----
0 1 1

3. Bitwise XOR [^]

When two different corresponding binary, the result is a

3 ^ 2 = 1
0 1 1
0 1 0
-----
0 0 1

4. bitwise [~]

For each binary data bit inverse, i.e., the 1 to 0, the 0 to 1

~3 = 4
0 1 1
-----
1 0 0

5. << left shift operator []

Each binary operand to the left a number of bits of all, the number of bits of a mobile "<<" specifies the right, lower 0s

Note: move to the left, to the right out of the air filled with a zero bit to the left is actually multiplied by the power of two

3 << 2 = 12 = 3 * 2^2 

0 1 1
------
0 1 1 0 0

6. The right-shift operator [] >>

All the various binary operand is ">>" Several left to the right, ">>" the number of bits specified by the right

Note: If the most significant bit 0, after the right, with 0 fill vacancies, if the highest bit 1, right after, with a fill vacancies, the right place is actually divided by a power of 2 several times.

3 >> 2 = 0 = 3/(2^2) 
0 1 1
-----
0 0 0 1 1

-4 >> 2 = -1
1 0 0 0  0 1 0 0
----------------
1 0 0 0  0 0 0 1 0 0

Ten, member operator

in: if found in the specified sequence, the return value True, False otherwise

>>>a = 10
>>>list1 = [1, 2, 4, 5]
>>>list2 =[20, 10, 15]
>>>print(a in list1)
False
>>>print(a in list2)
True

not in: returns True if value is not found in the specified sequence, otherwise it returns False

>>>a = 10
>>>list = [1, 2, 4, 5]
>>>list2 =[20, 10, 15]
>>>print(a not in list)
True
>>>print(a not in list2)
False

XI, the identity of the operator [to speak]

is: is determined from the two identifiers are not an object reference

>>> a = 1000
>>> b = a
>>> print( a is b)
True

is not: it determines the two identifiers are not referenced from different object

>>>a =1000
>>>b = 1000
>>>print(a is not b)
False

Note: the integer in the range [-5, 257), the interior of the python having a caching mechanism, so the data comparison will be less than this value may be some problems.

expand

1. string and numeric type can be directly output

>>>print(1)
1
>>>print("hello world")
hello world

2. Variable, no matter what type, number, Boolean, list. Dictionary can be directly output

>>> x=12
>>>print(x)
12
>>> list1 = [1, 2, 3]
>>> print(list1)
[1, 2, 3]

3. Output Formatting

>>> s = 'hello'
>>> s
'hello'
>>> x = len(s)
>>> print("the length of %s is %d"%(s,x))
the length of hello is 5

Note that when formatted output,

1% characters: Conversion described Start tag breaks;

2. If there is only one argument can also be bracketed without

The symbols of different format types used are different,

Integer% d% s% f floating-point string

XII branch statement

The computer was able to automate tasks, because they can do it conditional.

Thinking 1: Existing a demand, for example, enter the user's age, if less than 18, then print "Minors are not allowed to enter."

![370AA951-25BC-4374-B07E-4D6BA76BC694](/Users/zhangjiao/Library/Containers/com.tencent.qq/Data/Library/Application Support/QQ/Users/1838887021/QQ/Temp.db/370AA951-25BC-4374-B07E-4D6BA76BC694.png)

if 判断条件:
    执行语句...

Analyzing the condition of the if statement can be> (greater than), <(less than), == (equal),> = (greater than or equal), <= (less than or equal) to represent the relationship.

Requirement 2: If you are younger than 18, print "Minors are not allowed to enter", otherwise print "Welcome!"

if 判断条件:
    执行语句...
else:
    执行语句...

Analysis: to determine conditions: younger than 18, if set up, perform the "Minors are not allowed to enter", if set up, perform the "Welcome!"

age = 17
if age < 18:
    print("未成年人禁止进入")
else:
    print("欢迎光临!")

expand:

#可以使用ord 和chr两个内置函数用于字符与ASCII码之间的转换
>>> ord('a')
97
>>> chr(97)
a
Published 31 original articles · won praise 4 · Views 3523

Guess you like

Origin blog.csdn.net/qq_29074261/article/details/80016646