程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python learning 1: basic content

編輯:Python

List of articles

  • One 、Python standard
  • Two 、Python Basic norms
    • 2.1 notes
      • 1 Single-line comments
      • 2 Multiline comment
    • 2.2 Variable
      • 1 Define variable names
      • 2 Output variable name type
    • 2.3 Basic data type
      • 1. Numbers
      • 2. Boolean
    • 2.4 Value type conversion
    • 2.5 Input and output
      • 1. Input input(" Prompt text ")
      • 2. Input print(" Print text ")
  • 3、 ... and 、Python Operators and expressions
    • 3.1 Arithmetic operator
    • 3.2 Assignment operator
    • 3.3 Compare ( Relationship ) Operator
    • 3.4 Logical operators
    • 3.5 An operator
  • Four 、Python Flow control statement
    • 4.1 IF sentence
      • 1. if sentence
      • 2. if-else sentence
      • 3. if-elif-else sentence
      • 4. if nesting
    • 4.2 Loop statement
      • 1. while loop
      • 2. for loop
        • Method 1 With the help of ragne function
        • Method 2 Use it directly
    • 4.3 Cycle break break、continue、pass
      • 1 break Jump out of current loop
      • 2 continue End this cycle , Into the next loop
      • 3 pass Place holder , Don't do any numbers
  • 5、 ... and 、Python Lists and tuples
    • 5.1 Indexes
    • 5.2 section In the middle is a semicolon
    • 5.3 Sequence addition
    • 5.4 Multiplication
    • 5.5 Check whether the element is a member
    • 5.6 length 、 Maximum 、 minimum value
    • 5.7 Other functions
    • 5.8 list
      • 1. Creating and deleting lists
        • establish
          • Method 1 : Use it directly = establish
          • Method 2 : Create an empty list
          • Method 3 : Create a list of values
          • Method four : The derived type
        • Delete
      • 2. Access to the list
      • 3. Traversal of list
        • Method 1 : Use for
        • Method 2 : Use for and enumerate() Function implementation
      • 4. add to 、 Delete 、 modify
    • 5.9 Tuples
      • 1. establish
  • 6、 ... and 、Python Dictionaries and collections
    • 6.1 Dictionaries
      • 1. Create and delete
        • establish
        • Delete
      • 2. visit
        • 1. adopt key value
        • 2.Python The recommended method is through get function
        • 3. Ergodic dictionary items() function
      • 4. add to
      • 5. Delete
    • 6.2 aggregate
      • 1. establish
      • 2. add to
      • 3. Delete
      • 4. intersection &
      • 5. Combine |
      • 6. Difference set -

One 、Python standard

  1. Every import Only one module is introduced
  2. Don't use semicolons at the end of lines
  3. Don't use backslashes
  4. Pay attention to code indentation
  5. The named modules are all lowercase and separated by underscores
  6. Named packages are all lowercase , Underline is not recommended
  7. Name the class name , title case
  8. Name the inner class , Underline _+ title case
  9. Name the function , Class method , All lowercase , Underline to separate
  10. Named constants , All capitals , Underline to separate
  11. Module variables or functions that start with underscores are protected (import Will not import )
  12. Double underlined indicates private
  13. Don't start with a number , Keywords, etc
  14. Case sensitive
  15. __init__(): Represents a constructor

Two 、Python Basic norms

2.1 notes

1 Single-line comments

# notes 

Chinese annotation

# coding: code
# codign:utf-8

2 Multiline comment

Single quotation marks

'''
'''

Double quotes

"""
"""

2.2 Variable

1 Define variable names

Be careful with small letters l And capital letters O
grammar

 Variable name =value;

2 Output variable name type

print(type( Variable name ))

2.3 Basic data type

1. Numbers

  1. Integers
  2. Floating point numbers
  3. The plural
 The real number is 3.14 The plural is 12.5j
3.14+12.5j

2. Boolean

Python in ture Express 1 false Express 0

The following values are 0, But in if, perhaps while Behave as true

  1. False or None
  2. In value 0 Include 0.0、0、 imaginary number 0j
  3. Empty sequence , Contains characters 、 Empty ancestor 、 An empty list 、 An empty dictionary
  4. Custom instances , The object __bool__ The return method is False perhaps __len__ Method returns 0

2.4 Value type conversion

  1. x Round it up —>int(x)
  2. x To floating point —>float(x)
  3. Create a complex number complex(real[,imag])
  4. x Turn the string —>str(x)
  5. x To expression string —>repr(x)
  6. x The finite expression in the calculation string is converted into an object —>eval(x)
  7. x Integer to one character —>chr(x)
  8. Convert characters to integers ---->ord(x)
  9. Integer to 16 Base string hex(x)
  10. Integer to 8 Base string oct(x)

2.5 Input and output

1. Input input(“ Prompt text ”)

val=input(" Prompt text ")
val =int(input(" Prompt text "))

2. Input print(“ Print text ”)

print(" Print text ")
a=10
b=20
print(a,b)
》》》 10 20

Enter into folder

fp=open(r'D:\a.txt','a+')
print(" Input to txt Content ",file=fp)
fp.close()

3、 ... and 、Python Operators and expressions

3.1 Arithmetic operator

  1.  +
    
  2.  -
    
  3.  *
    
  4.  / 7/2=3.5 Python2.x yes 3
    
  5.  %
    
  6.  // 7//2=3 Take the whole part
    
  7.  ** power return x Of y Power 2**4 16
    

3.2 Assignment operator

The right is assigned to the left

  1. = x=y
  2. += x+=y---->x=x+y
  3. -= x-=y---->x=x-y
  4. = x=y---->x=x*y
  5. /= x/=y---->x=x/y
  6. %= x%/y---->x=x//y
  7. **=``````x**=y---->x=x**y
  8. //= x//=y---->x=x//y

3.3 Compare ( Relationship ) Operator

  1.  >
    
  2.  <
    
  3.  ==
    
  4.  !=
    
  5.  >=
    
  6.  <=
    

3.4 Logical operators

  1. and
  2. or
  3. not

3.5 An operator

  1. Bitwise and operation &
  2. Bitwise OR operation |
  3. Bitwise XOR ^
  4. Press the inverse operation ~
  5. Left shift operator <<
  6. Shift right operator >>

Four 、Python Flow control statement

4.1 IF sentence

1. if sentence

grammar

if expression :
Sentence block

2. if-else sentence

grammar

if expression :
Sentence block
else:
Sentence block

3. if-elif-else sentence

grammar

if expression :
Sentence block
elif expression :
Sentence block
else:
Sentence block

4. if nesting

if expression :
if expression :
Sentence block
else:
Sentence block
else:
Sentence block

4.2 Loop statement

1. while loop

while Conditional expression :
The loop body

2. for loop

Method 1 With the help of ragne function

for Iterative variable in object
The loop body
for i in range(101)
print(i)
>>>0 、1····100
range(start,end,step):
start Starting value , Do not write default is 0
end End value , End value , It doesn't contain
step: Specify the step size : The default is 1
Only one parameter is written as end
Two are start and end

Method 2 Use it directly

string =' Don't say I can't '
for ch in string
print(ch)
》》》
No
want
say
I
No
can

4.3 Cycle break break、continue、pass

1 break Jump out of current loop

2 continue End this cycle , Into the next loop

3 pass Place holder , Don't do any numbers

5、 ... and 、Python Lists and tuples

5.1 Indexes

Python You can start from the left or the right

The starting subscripts are 0 and -1

5.2 section In the middle is a semicolon

 grammar :sname[start:end:step]
sname: The name of the series
start: Starting position , The default is 0
end: End position , The default is length
step: : step , The default is 1
valekk = ["1","2", "3","4"]
print(valekk[1:2:1])
》》》['2']

5.3 Sequence addition

Use it directly + Must be of the same type

5.4 Multiplication

if __name__ == '__main__':
valekk = ["1","2", "3","4"]
print(valekk*5)
》》》
['1', '2', '3', '4', '1', '2', '3', '4', '1', '2', '3', '4', '1', '2', '3', '4', '1', '2', '3', '4']

5.5 Check whether the element is a member


if __name__ == '__main__':
values = ["1","2", "3","4"]
print('1' in values)
》》》
True

5.6 length 、 Maximum 、 minimum value

if __name__ == '__main__':
values = [1, 5, 4, 6, 7, 8, 9, 5, 3,2]
print(len(values)) # length
print(max(values)) # Maximum
print(min(values)) # minimum value
》》》
10
9
1

5.7 Other functions

  1. list() Convert sequence to list
  2. str() Convert sequence to string
  3. sum() Calculate the elements and
  4. sorted() Sort the elements
  5. reversed() Elements in the reverse order series
  6. enumerate() Combine the sequences into an index sequence , Use it more often for In circulation

5.8 list

1. Creating and deleting lists

establish

Method 1 : Use it directly = establish
listname=[123," test ",888]
Method 2 : Create an empty list
emptylist=[]
Method 3 : Create a list of values
listname=list(rang(10,20,2))
print(listname)
>>>[10,12,14,16,18]
Method four : The derived type
items=[Expression for var in range]
Expression : expression
var: Loop traversal
range : Generating function objects
items=[Expression for var in list]
according to list Generate new objects
price=[1,2,5,6]
eg:iteams=[int(x*0.5 for x in pritce)]

Delete

 Delete list
del listname

2. Access to the list

 Access list elements
Method 1 : direct print
Method 2 : By subscript
print(listname[2])
>>> 14

3. Traversal of list

Method 1 : Use for

for item in items:
print(item)

Method 2 : Use for and enumerate() Function implementation

for index ,item in enumerate(items)
print(items[index])
print(item)
print(index)

No line breaks print(,end=") ,end=" Output without line break

4. add to 、 Delete 、 modify

1. Additive elements

items.append( Elements )

items.insert( Location , Elements )

items.extend(seq) # take seq Spliced in items Back

2. Modifying elements

items[ Subscript ]= Element value

3. Remove elements

del items[ Subscript ]

items.remove(“ Elements ”)

4. Determine whether an element exists Statistics

items.count( Elements )>0 There is

5. Specifies the subscript of the first occurrence of the element

items.index( Elements )

6. Statistical elements and

sum(items[,start])
start: Start subscript

7. Sort

items.sort(key= Elements ,reverse=False)

reverse Default False: Ascending reverse=True: Descending

key=str.lower // Case insensitive Default case sensitive

8. Built in functions sorted() Sort
sorted(items,key=None,reverse=False)

5.9 Tuples

The difference from the list Tuples cannot become , All elements use () Enclose and separate with commas

items=( Elements 1, Elements 2, Elements 3)

Actually () Not its logo Comma is

items= Elements 1, Elements 2, Elements 3

1. establish

  1. Directly use the equals sign
  2. Create an empty tuple ltems=()
  3. Create a numeric tuple tuple(date) date You can make strings or functions
eg
items=tuple(range(1,5))
》》》
(1,2,3,4)
  1. Delete tuples del items
  2. Access elements items[ Subscript ]
  3. Access elements using enumerate(items)
for index ,item inenumerate(items)
print(item)
  1. Modify tuple —》 Reassign , This is not a real change
items[ Subscript ]= Elements
items= Tuples 1+ Tuples 2
When there is only one tuple connected, be sure to add a comma
iteams1=(1,2,3)
iteams2=(4,)
print(iteams1+iteams2)

6、 ... and 、Python Dictionaries and collections

6.1 Dictionaries

amount to java Of MAP
dictionary={‘key’:‘value’,‘key’:‘value’,‘key’:‘value’,‘key’:‘value’,}

  1. Get... By key
  2. Key value unique
  3. Dictionaries can be built without change
  4. The dictionary is out of order

1. Create and delete

establish

Method 1 : Use the equals sign directly

dictionary={‘key’:‘value’,‘key’:‘value’,‘key’:‘value’,‘key’:‘value’,}

Method 2 : Mapping function creates dictionary table

dictionary=dist(zip(list1,list2))

zip() function : Put multiple or one list 、 The corresponding positions of Yuanzu are combined into a dictionary

Method 3 : Specify a key value pair

dictionary=dict(key1=value1,…keyn=valuen)

eg
dictionary=dict( Elements =' value ',...keyn=valuen)

Method four : Specify all values as key

names=[' Elements 1',' Elements 2',' Elements 3']
items=names.forkeys(names)
print(items)
》》》
{[' Elements 1':None,' Elements 2':None,' Elements 3':None}

Delete

Delete

del items

eliminate

del.clear()

2. visit

1. adopt key value

value=items[key Elements ]

2.Python The recommended method is through get function

value=items.get(key Elements )
value=items.get(key Elements 1,key Elements 2)

3. Ergodic dictionary items() function

dictionary.items()

for item in dictionary.items()
print(item)

4. add to

dictionary[key]=value

5. Delete

del dictionary[“ Elements ”]

6.2 aggregate

No repetition

1. establish

Method 1 : Use it directly {} establish

setname={ Collection elements 1, Collection elements 2, Collection elements 3}

Method 2 : Use set() Function creation
setname=set( Content )

eg:
set1=set(" What destiny gives us is not the wine of despair , It's the cup of opportunity ")
print(set1)
set2=set([1,2,3])
print(set2)
set3=set((' Life is too short ',' Timely job hopping '))
print(set3)
》》》
{' life ', ' Alcohol ', ',', ' And ', ' Meeting ', ' and ', ' yes ', ' at ', ' People ', ' No ', ' I ', ' A cup of ', ' loss ', ' to ', ' shipment ', ' Give ', ' machine ', ' Of '}
{1, 2, 3}
{' Life is too short ', ' Timely job hopping '}

2. add to

setname.add( Element content )

3. Delete

setname.pop()// Remove the last one
setname.clear()
setname.remove( Elements )

4. intersection &

5. Combine |

6. Difference set -

 set1=set([1,2,3])
print(set1)
set2=set([3,4,5])
print(set2)
set3=set([5,6,7])
print(set3)
print(set1&set2)
print(set1|set2|set3)
print(set1-set2)
》》》
{1, 2, 3}
{3, 4, 5}
{5, 6, 7}
{3}
{1, 2, 3, 4, 5, 6, 7}
{1, 2}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved