1、 Sign in Official website Download the required version package
With window7 For example :
Right click to download the package (Windows x86-64 executable installer) Run as administrator
#!/usr/bin/python3
Before using variables , It needs to be assigned first .
Variable names can include letters 、 Numbers 、 Underline , Cannot start with a number
(\
) Escape character # example : let\'s go
If you want to print more special characters in the path , String preceded by r that will do .
example :D:\AIT\work\Software\xftp
have access to
str = r‘D:\AIT\work\Software\xftp’
Use idle(Python Editor for ),ctrl+n Create a new edit page ,f5 function
import random # random number
#print( random.randint(1,10) ) # produce 1 To 10 A random number of integer type
#print( random.random() ) # produce 0 To 1 Between random floating-point numbers
#print( random.uniform(1.1,5.4) ) # produce 1.1 To 5.4 Between random floating-point numbers , Interval can not be an integer
#print( random.choice('tomorrow') ) # Randomly select an element from the sequence
#print( random.randrange(1,100,2) ) # Generated from 1 To 100 The interval is 2 Random integer of
secret = random.randint(1,3)
print(" A random number for ",secret)
print('-------- strawberry A Work ---------')
temp = input(" Guess the number , Please write down a number :")
guess = int(temp)
while guess != secret:
temp = input(" Wrong guess. , Please enter again :")
guess = int(temp)
if guess == secret:
print(" You got it right !\n" + " Ouch , It's no use guessing right !")
else:
if guess >secret:
print(" The number is big ")
else:
print(" The number is smaller ")
print(" end ^_^")
>>> assert 3>7 #( Assertion : When the latter condition is false , Program crash pop-up exception AssertionError)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
assert 3>4
AssertionError
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'fa', 'guess', 'i', 'list1', 'list2', 'list3', 'member', 'member2', 'random', 'secret', 'temp']
>>>
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
dir() When a function has no arguments , Returns the variables in the current range 、 List of types of methods and definitions ; With parameters , Return the properties of the parameter 、 Method list .
>>> member = [1, 3, ' good ', 'stree’']
>>> member.append(' well ') # Append one to the end
>>> member
[1, 3, ' good ', 'stree', 'sdfasdf']
>>>
>>> member.extend([' Oh ',' ah ']) # Append the list to the end
>>> member
[1, 3, ' good ', 'stree', 'sdfasdf', ' Oh ', ' ah ']
>>>
>>> member.insert(1,'hei') # Where to insert
>>> member
[1, 'hei', 3, ' good ', 'stree', 'sdfasdf', ' Oh ', ' ah ']
>>>
>>> member[2]
3
>>>
`>>> member.remove(' ah ') # Delete a value
>>> member
[1, 'hei', 3, ' good ', 'stree', 'sdfasdf', ' Oh ']
>>> ``
>>> del member[1] # Delete the value of a bit
>>> member
[1, 3, ' good ', 'stree', 'sdfasdf', ' Oh ']
>>>
>>> member.pop() # Function to remove an element from the list ( Default last element ), And returns the value of that element .
' Oh '
>>> member
[1, 3, ' good ', 'stree', 'sdfasdf']
>>> member.pop(0) # You can also specify to move out
1
>>> member
[3, ' good ', 'stree', 'sdfasdf']
>>> member[1:3] # Copy out 1 To 3 The value of the position does not include 3, You can also use member[:3]、member[1:]、member[:]
[' good ', 'stree']
>>> member
[3, ' good ', 'stree', 'sdfasdf']
>>> member[:3]
[3, ' good ', 'stree']
>>> member[1:]
[' good ', 'stree', 'sdfasdf']
>>> member[:]
[3, ' good ', 'stree', 'sdfasdf']
>>> member2 = member[:] # Copy . If you use member2 = member Words member2 Because of member Change by change .
>>> member2
[3, ' good ', 'stree', 'sdfasdf']
>>>
>>> list1 = [123]
>>> list2 = [234]
>>> list1 < list2
True
>>> list1 = [123, 456]
>>> list2 = [234, 345]
>>> list1< list2 # Compare the first 0 position
True
>>> list1 * 3
[123, 456, 123, 456, 123, 456]
>>> 123 in list1
True
>>> 123 not in list1
False
>>> 1223 not in list1
True
>>>
>>> list3 = [123, [' Hello ', 123, 'hello'], 234]
>>> ' Hello ' in list3
False
>>> ' Hello ' in list3[1]
True
>>> list3[1]
[' Hello ', 123, 'hello']
>>>
>>> list3[1][1]
123
>>>
>>> list3 *= 5
>>> list3
[123, [' Hello ', 123, 'hello'], 234, 123, [' Hello ', 123, 'hello'], 234, 123, [' Hello ', 123, 'hello'], 234, 123, [' Hello ', 123, 'hello'], 234, 123, [' Hello ', 123, 'hello'], 234]
>>> list3.count(123) #123 stay list Is the number of times
5
>>>
>>>
>>> list3 = [234, ' Hello ', 123, 'hello']
>>> list3
[234, ' Hello ', 123, 'hello']
>>>
>>> list3.reverse() #list Median inversion
>>> list3
['hello', 123, ' Hello ', 234]
>>>
>>> list3.index(123) # Returns the position of the parameter in the list , Hit the first of these positions , Default all ranges
1
>>>
>>> list3*=3
>>> list3
['hello', 123, ' Hello ', 234, 'hello', 123, ' Hello ', 234, 'hello', 123, ' Hello ', 234]
>>> list3.index(123,3,7) # Query range 3~7, in 123 The location of
5
>>>
>>> list4 = [0,2,3,5,4,7,6,3]
>>> list4.sort() # Sort from small to large
>>> list4
[0, 2, 3, 3, 4, 5, 6, 7]
>>> list4.sort(reverse=True) # The reverse
>>> list4
[7, 6, 5, 4, 3, 3, 2, 0]
Tuples are immutable , Sorting cannot be increased or decreased
>>> tuple1 = (1,2,3,4,5,6,7,8)
>>> tuple1
(1, 2, 3, 4, 5, 6, 7, 8)
>>> tuple1[1]
2
>>> tuple1[3:]
(4, 5, 6, 7, 8)
>>> tuple2 = tuple1[:]
>>> tuple2
(1, 2, 3, 4, 5, 6, 7, 8)
>>>
>>> temp = (3,) # Creating a tuple must have a comma
>>> type(temp) # See variable types
<class 'tuple'>
>>>
>>> temp1 = (3)
>>> type(temp1)
<class 'int'>
>>>
>>> tuple1
(1, 2, 3, 4, 5, 6, 7, 8)
>>> tuple1 = tuple1[:2] + ('leo',) + tuple1[2:] # You can use splicing to make changes , Splice old tuples into new ones ( It's actually a change tuple1 Pointer position , Old pointer python It will be cleaned up automatically after a period of time .)
>>> tuple1
(1, 2, 'leo', 3, 4, 5, 6, 7, 8)
>>>
>>> 8 * (8,) # Follow list equally
(8, 8, 8, 8, 8, 8, 8, 8)
>>>
Use the built-in method , The original value will not change
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
>>> str1 = 'I love you'
>>> str1.capitalize() # title case
'I love you'
>>> str1.casefold() #
'i love you'
>>> str1.center(40)
' I love you '
>>> str1.count('o')
2
>>> str1
'I love you'
>>>
>
String built-in methods
>>> "{0} love {1}.{2}".format("i","python","com")
'i love python.com'
>>> "{a} love {b}.{c}".format(a="i",b="python",c="com")
'i love python.com'
>>> "{
{1}}".format(" No printing ")
'{1}'
>>> '{0:.1f}{1}'.format(27.58,'GB') # The colon marks the beginning of the formatting symbol , Print a fixed-point number one digit after the decimal point
'27.6GB'
>>>
>>> '%c' '%c' '%c' % (97, 98, 99)
'abc'
>>> '%s' % 'i love you'
'i love you'
>>> '%d + %d - %d' % (5,5,1)
'5 + 5 - 1'
>>>
>>> '%o' % 10
'12'
>>> '%10d' % 10
' 10'
>>> '%010d' % 10
'0000000010'
>>> '%-010d' % 10
'10 '
>>>
String formatting symbol meaning
Format operator auxiliary command
Python The escape character of and its meaning
>>> b = 'I love you'
>>> b
'I love you'
>>> b = list(b)
>>> b
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u']
>>> c = (1,1,2,3,4,8,13,21,34) # Tuples
>>> c = list(c) # Tuple to list
>>> c
[1, 1, 2, 3, 4, 8, 13, 21, 34]
>>>
>>> max(c)
34
>>> min(c)
1
>>> sum(c)
87
>>>
>>> c.append(2) # Append at the end 2
>>> sorted(c) # Sort , Do not change the source c Sequence
[1, 1, 2, 2, 3, 4, 8, 13, 21, 34]
>>>
>>> c
[1, 1, 2, 3, 4, 8, 13, 21, 34, 2]
>>> reversed(c) # reverse , The object returned is an iterator
<list_reverseiterator object at 0x0000000002D1E430>
>>> list(reversed(c)) # Convert to list
[2, 34, 21, 13, 8, 4, 3, 2, 1, 1]
>>>
>>> c
[1, 1, 2, 3, 4, 8, 13, 21, 34, 2]
>>> enumerate(c)
<enumerate object at 0x000000000303AE00>
>>> list(enumerate(c)) # enumeration
[(0, 1), (1, 1), (2, 2), (3, 3), (4, 4), (5, 8), (6, 13), (7, 21), (8, 34), (9, 2)]
>>>
>>> b
[3, 4, 6, 7, 8]
>>> list(zip(b,c)) # pack
[(3, 1), (4, 1), (6, 2), (7, 3), (8, 4)]
>>>
Python Call function , If there is no definition above, it cannot be called .
>>> def MyFirstFunction():
print('this is my first function')
print(' Thank you again ')
print(' thank CCTV')
>>> MyFirstFunction()
this is my first function
Thank you again
thank CCTV
>>>
>>>
>>> def MySecondFunction(name, parameter):
' This is the function document '
print(name + ' I like your ' + parameter)
>>> MySecondFunction.__doc__
' This is the function document '
>>> MySecondFunction(name = 'leo', parameter=' technology ')
leo I like your technique
>>>
>>>
>>> def MySecondFunction(name=' everyone ', parameter=' Ability '):
' This is the function document '
print(name + ' I like your ' + parameter)
>>> MySecondFunction()
Everybody, I like your ability
>>>
>>>
>>> def test(*params, exp = 8):
print(' The length of the parameter is ', len(params), exp);
print(' The second parameter is ', params[1]);
>>> test(1,'leo',3,5,74)
The length of the parameter is 5 8
The second parameter is leo
>>>
Example 1:
def MyFirstFunction(price , rate):
' This is the function document '
old_price = 20
print(' local variable old_price:',old_price)
global count # Define global variables
count = 10
final_price = price * rate
return final_price
old_price = float(input(' Please enter the original price :'))
print(' Global variables old_price:',old_price)
rate = float(input(' Please enter the discount rate :'))
new_price = MyFirstFunction(old_price, rate) # Call function calculation
print(' The price after discount is :', new_price)
print(' Custom global variables count Use global:',count)
Example 1 Running results
====================== RESTART: F:/python-test/function.py =====================
Please enter the original price :100
Global variables old_price: 100.0
Please enter the discount rate :0.5
local variable old_price: 20
The price after discount is : 50.0
Custom global variables count Use global: 10
>>>
>>> def fun1():
x = 5
def fun2():
nonlocal x # Make x Variable globalization
x *=x
return x
return fun2()
>>> fun1()
25
>>>
range
>>>range(10) # from 0 Start to 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # from 1 Start to 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # In steps of 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # In steps of 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # negative
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
Here are range stay for The use of , Recycle out runoob Every letter of :
>>>x = 'runoob'
>>> for i in range(len(x)) :
... print(x[i])
...
r
u
n
o
o
b
>>>
Built in functions filter
Filter out from 0 Start to 9,10 The odd of the numbers
>>> range(10) # from 0 Start to 9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(filter(None, [1, 0, False, True])) # Filter out "yes" and "no" None Of
[1, True]
>>>
>>> temp = range(10)
>>> def odd(x):
return x % 2
>>> show = filter(odd, temp) # Filter out odd numbers ( Numbers that are not even )
>>> list(show)
[1, 3, 5, 7, 9]
>>>
>>> list(filter(lambda x : x % 2,range(10))) # Filter out odd numbers ( Numbers that are not even ). Equivalent to the above usage
[1, 3, 5, 7, 9]
>>>
Built in functions map()
Meeting Map the specified sequence according to the function provided .
Machining parameter return sequence
>>> list(map(lambda x : x * 2, range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
Example 1: seek 5 The factorial ( iteration ) iteration : It's an activity that repeats the feedback process , Its purpose is usually to approach the desired goal or result . Every repetition of a process is called a “ iteration ”, The result of each iteration will be taken as the initial value of the next iteration .( loop )
def recursion(n):
result = n
for i in range(1, n):
result *= i
return result
number = int(input(' Please enter a positive integer :'))
result = recursion(number)
print('%d The factorial is :%d'% (number, result))
Example 1 Result :
===================== RESTART: F:/python-test/recursion.py =====================
Please enter a positive integer :5
5 The factorial is :120
>>>
Example 2: seek 5 The factorial ( recursive ) recursive , It is to call itself in the process of running .
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
number = int(input(' Please enter a positive integer :'))
result = factorial(number)
print('%d The factorial is :%d'% (number, result))
Example 2 result
===================== RESTART: F:/python-test/factorial.py =====================
Please enter a positive integer :5
5 The factorial is :120
>>>
Iteration execution speed > Recursive execution speed
Example 1: Iterative implementation
def fab(n):
n1 = 1
n2 = 1
n3 = 1
if n < 1:
print(' Input error :')
return -1
while (n -2) > 0:
n3 = n2 + n1
n1 = n2
n2 = n3
n -= 1
return n3
num = int(input(' Please enter a number :'))
result = fab(num)
if result != -1:
print(' in total %d A little rabbit ' % result)
Example 1 result :
======================= RESTART: F:/python-test/fab_1.py =======================
Please enter a number :30
All in all 832040 A little rabbit was born
>>>
Example 2: Recursive implementation ( Calls itself ) Mathematical function thought
def fab(n):
if n < 1 :
print(' Input error :')
return -1
if n==1 or n ==2:
return 1
else:
return fab(n-1) + fab(n-2)
num = int(input(' Please enter a number :'))
result = fab(num)
if result != -1:
print(' All in all %d A little rabbit was born ' % result)
Example 2: result
======================= RESTART: F:/python-test/fab_2.py =======================
Please enter a number :30
All in all 832040 A little rabbit was born
>>>
def hanoi(n, x , y, z):
if n == 1:
print(x, '- Move to ->', z)
else:
hanoi(n-1, x, z, y) # Before the n-1 A plate from x Move to y On
print(x, '- Move to ->', z) # Take the last plate from the bottom x Move to z On
hanoi(n-1, y, x, z) # take y Upper n-1 The plates move to z On
n = int(input(' Please enter the number of floors of Hanoi tower :'))
hanoi(n, 'x Left column ', 'y Center pillar ', 'z Right column ')
Input 4 Layer results :
====================== RESTART: F:/python-test/hannuota.py =====================
Please enter the number of floors of Hanoi tower :4
x Left column - Move to -> y Center pillar
x Left column - Move to -> z Right column
y Center pillar - Move to -> z Right column
x Left column - Move to -> y Center pillar
z Right column - Move to -> x Left column
z Right column - Move to -> y Center pillar
x Left column - Move to -> y Center pillar
x Left column - Move to -> z Right column
y Center pillar - Move to -> z Right column
y Center pillar - Move to -> x Left column
z Right column - Move to -> x Left column
y Center pillar - Move to -> z Right column
x Left column - Move to -> y Center pillar
x Left column - Move to -> z Right column
y Center pillar - Move to -> z Right column
>>>
key value
>>> dict1 = {
' Lining ':' Anything is possible ',' Nike ':'jus do IT',' Adidas ':'imossible is nohing'}
>>> print(' Nike's slogan is :',dict1[' Nike '])
Nike's slogan is : jus do IT
>>>
>>> dict2 = {
1:'ont', 2:'two', 3:'three'} # Create a dictionary
>>> dict2[2]
'two'
>>> dict3 = {
} # Create an empty dictionary
>>> dict3
{
}
>>>
>>> dict3 = dict((('f',70), ('i',99), ('3',80),('4',9))) # Create a dictionary
>>> dict3
{
'f': 70, 'i': 99, '3': 80, '4': 9}
>>>
>>> dict4 = dict( Hello =' All over the world ', The movie =' It's beautiful ') # Create a dictionary
>>> dict4
{
' Hello ': ' All over the world ', ' The movie ': ' It's beautiful '}
>>>
>>> dict4[' The movie '] = ' What is it? ' # modify key Corresponding value
>>> dict4
{
' Hello ': ' All over the world ', ' The movie ': ' What is it? '}
>>>
>>> dict4[' Little turtle '] = ' What is it again? ' # Add Dictionary key -value
>>> dict4
{
' Hello ': ' All over the world ', ' The movie ': ' What is it? ', ' Little turtle ': ' What is it again? '}
>>>
>>> dict1 = {
}
>>> dict1
{
}
>>> dict1.fromkeys((1,2,3,4))
{
1: None, 2: None, 3: None, 4: None}
>>> dict1 = dict1.fromkeys(range(32), ' Fabulous ')
>>> dict1
{
0: ' Fabulous ', 1: ' Fabulous ', 2: ' Fabulous ', 3: ' Fabulous ', 4: ' Fabulous ', 5: ' Fabulous ', 6: ' Fabulous ', 7: ' Fabulous ', 8: ' Fabulous ', 9: ' Fabulous ', 10: ' Fabulous ', 11: ' Fabulous ', 12: ' Fabulous ', 13: ' Fabulous ', 14: ' Fabulous ', 15: ' Fabulous ', 16: ' Fabulous ', 17: ' Fabulous ', 18: ' Fabulous ', 19: ' Fabulous ', 20: ' Fabulous ', 21: ' Fabulous ', 22: ' Fabulous ', 23: ' Fabulous ', 24: ' Fabulous ', 25: ' Fabulous ', 26: ' Fabulous ', 27: ' Fabulous ', 28: ' Fabulous ', 29: ' Fabulous ', 30: ' Fabulous ', 31: ' Fabulous '}
>>> for eachkey in dict1.keys(): # Print keys
print(eachkey)
0
1
2
3
……
30
31
>>> for eachkey in dict1.values(): # Print values
print(eachkey)
Fabulous
Fabulous
……
Fabulous
>>> for eachkey in dict1.items(): # Print everything
print(eachkey)
(0, ' Fabulous ')
(1, ' Fabulous ')
(2, ' Fabulous ')
(3, ' Fabulous ')
……
(31, ' Fabulous ')
>>> print(dict1[31])
Fabulous
>>> print(dict1[32])
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
print(dict1[32])
KeyError: 32
>>>
>>> print(dict4.get(32)) # get Get value
None
>>> dict4.get(32)
>>> print(dict1.get(3, 'meiyou')) # If there is a value, it can be obtained by normal printing value
Fabulous
>>> print(dict1.get(32, 'meiyou')) # You can return if it does not exist ‘ No, ’
meiyou
>>>
>>> 31 in dict1 # Use in Find out if the member exists
True
>>> 32 in dict1
False
>>>
>>> dict1.clear() # Empty dictionary
>>> dict1
{
}
>>>
# Use clear The relevant dictionary table will be cleared , If you directly empty other associated table data, it still exists , Here is an example
>>> a = {
'name', 'leo'}
>>> b = a
>>> b
{
'leo', 'name'}
>>> a = {
}
>>> a
{
}
>>> b
{
'leo', 'name'}
>>> a = b
>>> a.clear()
>>> b
set()
>>> a
set()
>>> a = {
1:'noe', 2:'two', 3:'three'}
>>> b = a.copy() # Copy
>>> b
{
1: 'noe', 2: 'two', 3: 'three'}
>>> c = a # assignment , Just put a label on the same data
>>> c
{
1: 'noe', 2: 'two', 3: 'three'}
>>>
>>> id(a)
50054720
>>> id(b)
50329216
>>> id(c)
50054720
>>>
>>> c[4] = 'four'
>>> c
{
1: 'noe', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{
1: 'noe', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{
1: 'noe', 2: 'two', 3: 'three'}
>>>
>>> a.pop(4) # Specify to pop up a key value
'four'
>>> a
{
1: 'noe', 2: 'two', 3: 'three'}
>>> a.popitem() # Pop up one randomly key value
(3, 'three')
>>> a
{
1: 'noe', 2: 'two'}
>>> a.setdefault('xiaobai') # Add one key
>>> a
{
1: 'noe', 2: 'two', 'xiaobai': None}
>>> a.setdefault(3, 'five') # Add one key value
'five'
>>> a
{
1: 'noe', 2: 'two', 'xiaobai': None, 3: 'five'}
>>> b = {
' The small white ': 'dog'}
>>> a.update(b) # b Map updates to another dictionary a In the middle
>>> a
{
1: 'noe', 2: 'two', 'xiaobai': None, 3: 'five', ' The small white ': 'dog'}
>>>
Is chaotic , Cannot index an element .
>>> set1 = set([1,2,3,4,5,5,5]) # Create a collection to automatically weed out duplicate values
>>> set1
{
1, 2, 3, 4, 5}
>>>
Immutable set :
>>> num3 = frozenset([1,2,3,4,5]) # Define an immutable set
>>> num3.add(0)
Traceback (most recent call last):
File "<pyshell#148>", line 1, in <module>
num3.add(0)
AttributeError: 'frozenset' object has no attribute 'add'
>>>
Built-in methods :
>>> num2 = {
1,2,3,4,5,6,7,8}
>>> num2
{
1, 2, 3, 4, 5, 6, 7, 8}
>>> 1 in num2
True
>>> 9 in num2
False
>>> num2.add(9) # add to
>>> num2
{
1, 2, 3, 4, 5, 6, 7, 8, 9}
>>>
>>> num2.remove(1) # remove
>>> num2
{
2, 3, 4, 5, 6, 7, 8, 9}
>>>
Example : If you want to eliminate duplicate numbers in the list [1,2,3,4,5,5,3,2,1,0]
Method 1
for Circular judgement
>>> num1 = [1,2,3,4,5,5,3,2,1,0]
>>> num1
[1, 2, 3, 4, 5, 5, 3, 2, 1, 0]
>>> temp = []
>>> for each in num1:
if each not in temp:
temp.append(each)
>>> temp
[1, 2, 3, 4, 5, 0]
>>>
Method 2
Use set set The function automatically removes duplicate numbers , But the set is unordered , Although the repeated numbers are eliminated, the results are out of order
>>> num1 = [1,2,3,4,5,5,3,2,1,0]
>>> num1
[1, 2, 3, 4, 5, 5, 3, 2, 1, 0]
>>> num1 = list(set(num1)) # Use set set The function automatically removes duplicate numbers , But the set is unordered , Although the repeated numbers are eliminated, the results are out of order
>>> num1
[0, 1, 2, 3, 4, 5]
>>>
List derivation
[x*y for x in range(1,5) if x > 2 for y in range(1,4) if y < 3]
His order of execution is :
for x in range(1,5)
if x > 2
for y in range(1,4)
if y < 3
x*y
>>> # List derivation
>>> a = [i for i in range(100) if not(i % 2) and i % 3]
>>> a
[2, 4, 8, 10, 14, 16, 20, 22, 26, 28, 32, 34, 38, 40, 44, 46, 50, 52, 56, 58, 62, 64, 68, 70, 74, 76, 80, 82, 86, 88, 92, 94, 98]
>>> # Dictionary derivation
>>> b = {
i:i %2 ==0 for i in range(10)}
>>> b
{
0: True, 1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False}
>>> # Set derivation
>>> c = {
i for i in [1, 1, 2, 3, 4, 5, 5, 6, 7, 3, 2, 1]}
>>> c
{
1, 2, 3, 4, 5, 6, 7}
File open mode :
File object method :
>>> f = open('F:\\python-test\\ file \\ Heart meridian .txt') # Open file
>>> f.read(5) # Read file contents , If no value is given, read all , Put the pointer to the end
' The original Heart Sutra '
>>> f.tell() # Return to location
9
>>> f.seek(2, 0) # Move the file pointer in the file f.seek(offset, from)(0 Represents the starting location of the file ,1 Represents the current location ,2 End of representative document ) The offset offset Bytes
2
>>> f.readline() # Read from the file and return a line
' The original text \u3000 \n'
>>> f.seek(0,0) # Put the pointer to the start position
0
# It can be read as a list
>>> lines = list(f)
>>> for each_line in lines:
print(each_line)
The original Heart Sutra
……
# The official recommendation is direct iterative reading ( Efficient )
>>> f.seek(0,0)
0
>>> for each_lin in f:
print(each_lin)
The original Heart Sutra
……
>>> f = open('F:\\python-test\\ file \\ Heart meridian .txt','w')
>>> f.tell()
0
>>> f.write('I love hello wold') # Open the file as a write , The existing file will be overwritten
17
>>> f.close()
>>>
>>> f = open('F:\\python-test\\ file \\ Heart meridian .txt','a') # Open in write mode , If the file exists , Write... At the end
>>> f.read()
>>> f.write('I love hello wold')
17
>>> f.close()
test.txt
Hello :I love hello wold1
Not good. :I love hello wold2
Hello :I love hello wold3
Not good. :I love hello wold4
Hello :I love hello wold5
=======================
Not good. :I love hello wold6
Hello :I love hello wold7
Not good. :I love hello wold8
Hello :I love hello wold9
=======================
Not good. :I love hello wold0
Hello :I love hello wold~
Not good. :I love hello wold!
Hello :I love hello wold?
Not good. :I love hello wold.
Press ‘ Not good. ’、‘ Hello ’: After that, it is divided and stored in different files , One ==== Split into one file
F:/python-test/file.py
# Save the file
def save_file(boy, girl ,count):
file_name_boy = 'F:\\python-test\\ file \\' + 'boy_' + str(count) + '.txt'
file_name_girl = 'F:\\python-test\\ file \\' + 'girl_' + str(count) + '.txt'
boy_file = open(file_name_boy, 'w') # Open a file to write
girl_file = open(file_name_girl, 'w')
boy_file.writelines(boy) # Write string to file “ Sequence ”
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
# Split file
def split_file(file_name):
f = open(file_name)
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != '======':
# We do string segmentation here
(role, line_spoken) = each_line.split(':', 1) # Split once , Returns the list of concatenated substrings after slicing .
if role == ' Hello ':
boy.append(line_spoken)
if role == ' Not good. ':
girl.append(line_spoken)
else:
# File split save , meet '======' preservation
save_file(boy, girl, count)
boy = []
girl = []
count += 1
save_file(boy, girl, count)
f.close()
split_file('F:\\python-test\\ file \\test.txt')
The successful running :
import os
Easy to use :
>>> import os
>>> os.getcwd() # Get the current working directory
'F:\\python-test'
>>> os.chdir('F:\\python-test\\working') # Change working directory
>>> os.getcwd()
'F:\\python-test\\working'
>>> os.listdir()
['fab_1.py', 'fab_2.py', 'factorial.py', 'file.py', 'function.py', 'hannuota.py', 'print(ifelse).py', 'recursion.py']
>>> os.makedirs('F:\\python-test\\working\\A\\B')
>>> os.listdir()
['A', 'fab_1.py', 'fab_2.py', 'factorial.py', 'file.py', 'function.py', 'hannuota.py', 'print(ifelse).py', 'recursion.py']
>>> os.curdir
'.'
>>> os.listdir(os.curdir)
['fab_1.py', 'fab_2.py', 'factorial.py', 'file.py', 'function.py', 'hannuota.py', 'print(ifelse).py', 'recursion.py']
>>>
Examples of use :
>>> os.path.basename('F:\\python-test\\working\\factorial.py')
'factorial.py'
>>> os.path.dirname('F:\\python-test\\working\\factorial.py')
'F:\\python-test\\working'
>>>
>>> os.listdir(os.path.dirname('F:\\python-test\\working\\'))
['fab_1.py', 'fab_2.py', 'factorial.py', 'file.py', 'function.py', 'hannuota.py', 'print(ifelse).py', 'recursion.py']
>>>
>>> os.path.split('F:\\python-test\\working\\factorial.py')
('F:\\python-test\\working', 'factorial.py')
>>>
>>> os.path.splitext('F:\\python-test\\working\\factorial.py')
('F:\\python-test\\working\\factorial', '.py')
>>> import time
>>> time.localtime(os.path.getatime('F:\\python-test\\working\\factorial.py'))
time.struct_time(tm_year=2020, tm_mon=11, tm_mday=5, tm_hour=15, tm_min=42, tm_sec=43, tm_wday=3, tm_yday=310, tm_isdst=0)
>>>
>>> os.path.exists('F:\\python-test\\working\\factorial.py')
True
>>> os.path.ismount('F:\\')
True
>>> os.path.ismount('F:\\python-test\\')
False
>>>
Zero Basics 2
Study address
Data address
Pymongo