Python Basics (i)

Source: Internet
Author: User
Tags arithmetic operators bitwise logical operators


The default Python file is: file name. py

#!/usr/bin/env python
# Coding=utf-8 support for Chinese (remember: there are no spaces on both sides of the equals sign)
Execute Python file:
[email protected] desktop]# python test1.py

[Email protected] desktop]# chmod +x test1.py
[Email protected] desktop]#./test1.py

Variable: a symbol pointing to memory
Different file systems also belong to different types it works on disk
Python: Strongly typed dynamic Language "variable can be substituted, including the type of the variable"

Data types fall into two main categories: numeric types and String types
>>> A = 1
>>> type (a)
<type ' int ' >
>>> a= ' str '
>>> type (a)
<type ' str ' >
Different data types cannot be transformed
>>> a= ' Hello '
>>> b= ' World '
>>> a+b
' HelloWorld '
In Python, as in other languages: data loss when converting from high-precision to low-precision, not when converting low-precision to high-precision

program = data structure + algorithm
Priority: Monocular > Binocular (Single-mesh:!) Binocular operator: +-*/; there is no trinocular operator in Python)
Arithmetic operators > Bit manipulation operators > Comparison operators > Logical operators
Arithmetic operators: +-*/%
Bitwise manipulation Operators: << >> & ^ | ~
Comparison operators: < <= > >=! =
Logical operator: and or not assignment =

() Priority Assignment = least priority

An expression:
Division Operation:
>>> 10/3
3
>>> 10/3.0
3.3333333333333335
>>> 10.0/3
3.3333333333333335
Power Operation:
>>> 2**4
16
Division Rounding Operations:
>>> 10//3.0
3.0
>>> 10.0//3
3.0
>>> 10//3
3

Modulo operation:
>>> 10%3
1
>>> 10%3.0
1.0


Bitwise AND & are all true
or | There is a truth to be true
Xor ^ has two different when it is true, the same is false


>>> 2<<3 00010 shift left 3-bit 10 000=2**4
16
>>> 2>>3 00010 Right shift three bit out of bounds is zero
0
>>> 3&2 bitwise with: 11&AMP;10 = 10
2
>>> 3^2:11^10 = 01
1
>>> 3|2 Bitwise OR: 11|10 = 11
3



Program Structure:
The IF statement can only go into one branch and execute out of the IF statement only one else can have multiple elif
The branch statement has only one if
Loop statement: While for break continue and the loop can have else
While condition:
Expression
For item in iterators (lists, tuples, etc.)
Expression
Break exits the entire loop body
Continue exiting the current loop

Python's built-in containers are: lists, tuples, dictionaries, sets and,

>>> a= [1,4,5, ' Lo '] # elements in #定义一个列表 list are not required and the list can be nested
>>> type (a) # #type () View types
<type ' list ' >

Range () gets a list
>>> Range (0,2)
[0, 1]
>>> dir (a) # #可以查看对于一个容器能够执行的操作
[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __delitem__ ', ' __delslice__ ', ' __doc__ ', ' __eq__ ', ' __format_ ' _ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __getslice__ ', ' __gt__ ', ' __hash__ ', ' __iadd__ ', ' __imul__ ', ' __init_ _ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ' , ' __reversed__ ', ' __rmul__ ', ' __setattr__ ', ' __setitem__ ', ' __setslice__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ' ', ' append ', ' count ', ' extend ', ' index ', ' Insert ', ' pop ', ' remove ', ' reverse ', ' sort ']

>>> Help (A.count) # #查看帮助
>>> A.append (3)
>>> A
[1, 3, [1, 2, 3], 3]
>>> A.count (3) # #统计某个数在列表中出现的次数
2
>>> A.extend (b) # #将两个容器追加到一个当中
>>> A
[1, 3, [1, 2, 3],, 3, ' Hello ', ' world ', 23]

>>> B.insert (2,45) inserts a given number before the subscript
>>> b
[' Hello ', ' world ', 45, 23]

>>> B.index (23) returns the subscript of the number
3

>>> B.remove (45) Delete a number
>>> b
[666, ' Hello ', ' world ', 23]


>>> b=[1,23,24,13,24,44,] # #pop Delete a number of subscripts and return the number
>>> B.pop ()
44
>>> b
[1, 23, 24, 13, 24]
>>> B.pop (2)
24
>>> b
[1, 23, 13, 24]

>>> B.reverse () displays the number of numbers in the list in reverse order
>>> b
[24, 13, 23, 1]

>>> B.sort () arranges the numbers in the list by size
>>> b
[1, 13, 23, 24]
>>> in a # #判断某一个元素在列表中
True

>>> A
[1, 3, ' Lo ', [1, 2, 3]]
>>> Len (a) # #得到列表长度
4
>>> del a[2] # #del Delete the list of elements in the table below
>>> A
[1, 3, [1, 2, 3]]


List slices: # #列表切片不会改变列表的本身,
LI[A:B:C] starts with subscript A and ends with subscript B, but does not contain b,c represented as tunic
>>> A
[1, 3, [1, 2, 3],, 3, ' Hello ', ' world ', 23]

>>> A[1:7]
[3, [1, 2, 3], a, 3, ' Hello ', ' world ']

>>> A[:6]
[1, 3, [1, 2, 3], a, 3, ' hello ']

>>> a[::-1] # #实现逆序显示一个列表:
[23°c, ' World ', ' Hello ', 3, 45, [1, 2, 3], 3, 1]

###
>>> A
[1, 3, [1, 2, 3],, 3, ' Hello ', ' world ', 23]
>>> a1=a[:]
>>> a[2][1]=100
>>> A
[1, 3, [1, 3], GB, 3, ' Hello ', ' world ', 23]
>>> A1
[1, 3, [1, 3], GB, 3, ' Hello ', ' world ', 23]
###### #注意: A list assignment is equivalent to referencing a value that is not the same as a slice assignment
>>> L2
[4, 5, 6]
>>> L5=L2
>>> ID (L2)
11948832
>>> ID (L5)
11948832
>>> l6=l2[:]
>>> ID (L6)
11948976




Tuples: Tuples are immutable objects and cannot be modified for the contents of tuples.
>>> c= (1,23,45)
>>> type (c)
<type ' tuple ' >

Tuples can only perform: Count,index operations, and tuples support subscripts and slices, depending on the immutable nature of the tuple.
>>> C
([1.23, A, ' hello '], [34, 54])
>>> c[0][2]=230
>>> C
([1.23, 34, 230], [34, 54])
Indicates that the tuple's immutable is relative.

Set and:
>>> C
Set ([1, 2, ' Kitty ', +]) # #定义一个集和
>>> type (c)
<type ' Set ' >

>> a = set () # #定义一个空集和
>>> type (a)
<type ' Set ' >

>>> c={} # #定义出来的为字典
>>> type (c)
<type ' Dict ' >


Set and maintain the set and nature of Mathematics: disorder, uniqueness,
>>> d={1,3,1,2, ' Kitty ', 23,1, ' Hello '}
>>> D
Set ([1, 2, 3, ' Kitty ', [+], ' hello '])
Set and not supported slices
>>> C.add (+) # #集和元素的添加
>>> C
Set ([1, 2, +, ' Kitty ', 21])
>>> ([C.update, ' World ',]) # #增加一个集和
>>> C
Set ([1, 2, +, +, ' kitty ', +, +, ' world ')


>> C.remove # #删除集和中一个元素 But the element does not exist in the set and the Times wrong
>>> C
Set ([1, 2, +, ' kitty ', +, +, ' world ')
>>> C.remove (43)
Traceback (most recent):
File "<stdin>", line 1, in <module>
keyerror:43

>>> C.discard # #删除一个元素, no action is taken without the element.
>>> C
Set ([1, 2, +, ' kitty ', +, +, ' world ')

>>> C.pop () # #随机的删除集和中的某个元素.
2
>>> C # #清除某个集和
Set ([+, ' Kitty ', +, +, ' world ')
>>> C.clear ()
>>> C
Set ([])
Operation of the set and:
Difference set: Difference # #求出差集 A-B
Difference_update # #求出差集, but modified the original set and does not return a value
>>> C
Set ([' World ', 2, 1, 45, 23])
>>> D
Set ([1, 2, 3, ' Kitty ', [+], ' hello '])
>>> C.difference (d)
Set ([' World ', 45])
>>> C.difference_update (d)
>>> C
Set ([' World ', 45])

Intersection: Intersection
Intersection_update
&
>>> C.intersection (d)
Set ([1, 2, 23])
>>> C.intersection_update (d)
>>> C
Set ([1, 2, 23])
>>> c&d
Set ([1, 2, 23])

Union: Unions |
>>> C.union (d)
Set ([1, 2, 3, ' Kitty ', ', ', ' World ', ' hello '])
>>> c|d
Set ([1, 2, 3, ' Kitty ', ', ', ' World ', ' hello '])

Determine if there is a intersection: Isdisjoint View two sets and whether there are intersections, returns a Boolean value
>>> C
Set ([' World ', 2, 1, 45, 23])
>>> D
Set ([1, 2, 3, ' Kitty ', [+], ' hello '])
>>> C.isdisjoint (d)
False
>>> e={' lll ', 666}
>>> C.isdisjoint (E)
True

Conversions between containers:
Tuples and lists:
>>> (t=)
>>> type (t)
<type ' tuple ' >
>>> List (t)
[1, 2, 3]
>>> T1.append (24)
>>> T1
[1, 2, 3, ' Hello ', 24]
>>> T
(1, 2, 3, ' hello ')



>>> t=tuple (T1)
>>> T1
[1, 2, 3, ' Hello ', 24]


Conversion of lists to sets and
>>> l=[1,22,23, ' hello ']
>>> A=set (L)
>>> A
Set ([1, ' Hello ', 22, 23])
>>> A.add (45)
>>> A
Set ([1, A, ' hello ', 22, 23])
>>> L
[1, +, +, ' hello ']
>>> L=list (a)
>>> L
[1, A, ' hello ', 22, 23]
>>> P=set (t)
>>> P
Set ([1, 2, 3, ' hello '])

Set,list,tuple, three functions can be converted, but because of the nature of the set, when the list or tuple is converted to set, there are duplicate elements, then delete.

Dictionary:
D=dict (); d= ("Key": "Value")
The key value in D is hash-able. Key is unique.
>>> D
{' Age ': +, ' name ': ' Tom '}

>>> D.keys ()
[' Age ', ' name ']

>>> d.values ()
[+, ' Tom ']

>>> it= D.iterkeys () Iterkeys returns all keys of the dictionary as an iterator
>>> It.next ()
' Age '
>>> It.next ()
' Name '

>>> it2=d.items () items returns a list that is paired out in the form of tuples
>>> it2
[(' Age ', ' ' "'), (' Name ', ' Tom ')]

>>> for I in D.keys ():
... print I,d[i]
...
Age 23
Name Tom

>> for K,v in D.items ():
.. print K, V
...
Age 23
Name Tom
>>> d[' sex ']=2 # # #给字典增加一个值
>>> D
{' Age ': ' + ', ' name ': ' Tom ', ' Sex ': 2}

############ #注意: The difference between a reference value and a copy:
>>> D
{' Age ': ' + ', ' name ': ' Tom ', ' Sex ': 2}
>>> D1=d
>>> d1[' age ']=66
>>> D1
{' Age ': $, ' name ': ' Tom ', ' Sex ': 2}
>>> D
{' Age ': $, ' name ': ' Tom ', ' Sex ': 2}
>>> d2=d.copy ()
>>> D2
{' Age ': $, ' name ': ' Tom ', ' Sex ': 2}
>>> d2[' age ']=99
>>> D2
{' Age ': The ' name ': ' Tom ', ' Sex ': 2}
>>> D
{' Age ': $, ' name ': ' Tom ', ' Sex ': 2}
>>> ID (d)
9777488
>>> ID (d1)
9777488
>>> ID (D2)
10605344

List resolution:
>>> li=[1, 2, 3, 4, 5]
>>> li1=[i+1 for i in Li]
>>> Print Li1
[2, 3, 4, 5, 6]


>>> l1=[1,2,3]
>>> l2=[4,5,6]
>>> l3= (i+1 for i in L1)
>>> L3
<generator Object <genexpr> at 0x9b60f0> # #返回的是一个迭代器
>>> L3.next ()
2
>>> L3.next ()
3
>>> L3.next ()
4
Iterator (iterator): executes once to the result "passive" (he is not the equivalent of the cycle of "active") it is an inert



This article is from the "11715322" blog, please be sure to keep this source http://11725322.blog.51cto.com/11715322/1788970

Python Basics (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.