Python Basics (local, global variables, functions, file operations)

Source: Internet
Author: User

Python Basics (local, global variables, functions, file operations)

Local variables can be used with return values
Global variables
If a function has a return value, it has no meaning if it is saved with this variable before calling the function.
Global
If you add global declarations to a global variable in a local variable
Wendu = 0
def test1 ():
Global Wendu
Wendu = 33

Def test2 ():
Print ("%d"%wendu)
#test1 ()
Test2 () result is 0

Wendu = 0
def test1 ():
Global Wendu
Wendu = 33

Def test2 ():
Print ("%d"%wendu)
Test1 ()
Test2 () result is 33

A global variable can be preceded by a function and cannot be followed after a call
Local variables are higher than global variables
In a function, if you assign a variable with the same name as a global variable, the default is to define a variable
It's just that the variable name is the same as the global white energy name.
You can add g_.

If the list dictionary is treated as a global variable without adding a global declaration, you can use the

The default parameter can be multiple only in the back
def test (A,B=100) can be transmitted, or can not be transmitted by default, transmitted with the incoming
def test (a,b=100) default parameters
? ? Return a + b
b = Test (10)
Print (b)
The default function can be set to whom to pass multiple times.
Eg:def Test (A,B=11,C=33):
?? Test (11,12) 12 will give B
?? Test (11,c =12) Argument 12 is called named parameter C is named parameter when passed in

+ name args official
Indefinite length parameter
The number of formal and argument parameters is greater than the number of arguments in the indeterminate length function.
There is only one element in a meta-ancestor to add one to the back,
Split tuple
Split Package
**kwargs
Split xxx

ID (address of memory space) reference
A = 100
b =a Public One address

Not the same in C language A = b = 1002 Addresses

mutable types and immutable types
Immutable numeric string tuple
Variable List sub-code

Recursive functions
def getnum (num):
? ? If num >1:
?? ?? ? Return num * Getnum (NUM-1)
? ? Else
?? ?? ? Return num

anonymous functions
Lambda Parameters: Formulas
variable = lambda x,y:x+y
Variable ()
Sorting for dictionaries
Stus = [{},{},{}]
Stus.sort (key= lambda x:x["key"] or ["value"])

def test (A,b,func)
? ? result = Func (A, B)
? ? Print (Result)
Test (11,12,lambda x,y:x+y)

Python3 string Conversion to command
Eval () minus "" equals statement

Manipulation of strings
1.find ()? Where does the return exist? Does not exist return-1
2.index ()? Where does the index return? Do not participate in the error
3.rfind ()?? from right to left
4.rindex ()
5.count () Occurrences
6.replace () Replace. Replace ("", "" if there are duplicates inside the string, this seat can be followed by the first few)
?? Do not write default duplicates are modified
7.split () Cut Split ("") cut with consumption
8.capitalize () The first uppercase of the string
9.title ()? Capitalize the first letter of each word
10.startswith () Judging the beginning of the string
11.endsswith () Judgment end suffix
12.upper () all uppercase
13.lower () both lowercase
14.rjust () Right-justified
15.ljust () Align Left
16.center () inside can be with width
17.lstrip () Remove the left space
18.rstrip () Delete the right space
19.partition (str) divided into three parts
20.rpartition (str) Start split right
21.splitline () line break \ n Meet programming short string
22.isalpha () judgment is all letters
22.isdigit () judgment is purely digital
23.isalnum () contains only letters and numbers
24.isspace () is not a pure space
25.join () string to connect a thing together

The operation of the file
f = Open ("", "W")
R read-only pointer at the beginning of the file
W Write only existing overwrite does not exist create
A open a file for append? If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to.
RB binary open a file read-only pointer at the beginning
WB and so far write
AB binary Append
A + read and write presence at the end
rb+
wb+
ab+
F.close ()

If Open is opening a file, then you can not thank the open mode, that is, write only? Open (' Test.txt ')
If you read it more than once, the data that you read later begins at the point where you read it last.
Renaming of files import os
Os. Rename ()
Deletion of files import os
Os.remove ()
Backup of files
#coding =utf-8

Oldfilename = input ("Please enter the name of the file to be copied:")

OldFile = open (Oldfilename, ' R ')

If you open the file if OldFile: Extract the suffix of the file

Fileflagnum = Oldfilename.rfind ('. ')
If Fileflagnum > 0:
Fileflag = Oldfilename[fileflagnum:]

Organize a new file name

NewFileName = Oldfilename[:fileflagnum] + ' [copy] ' + Fileflag

Create a new file

NewFile = open (NewFileName, ' W ')

Copy data from an old file to a new file in a row

For linecontent in Oldfile.readlines ():
Newfile.write (linecontent)

Close File

Oldfile.close ()
Newfile.close ()
?
Random Read and write of files

Open a file that already exists

f = open ("Test.txt", "R")
str = f.read (3)
Print "Read data is:", str

Find Current Location

Position = F.tell ()
Print "Current file location:", Position

str = f.read (3)
Print "Read data is:", str

Find Current Location

Position = F.tell ()
Print "Current file location:", Position

F.close ()
?
Operation of the file
If you need to operate from another location while reading and writing files, you can use Seek ()
Seek (offset, from) has 2 parameters
Offset: Offsets
From: direction
0: Indicates the beginning of the file
1: Indicates the current position
2: Indicates end of file
Demo: Set the location to: from the beginning of the file, offset by 5 bytes

Open a file that already exists

f = open ("Test.txt", "R")
str = f.read (30)
Print "Read data is:", str

Find Current Location

Position = F.tell ()
Print "Current file location:", Position

Reset Location

F.seek (5,0)

Find Current Location

Position = F.tell ()
Print "Current file location:", Position

F.close ()
?

Demo: Set the location to: from the end of the file, at 3 bytes

Open a file that already exists

f = open ("Test.txt", "R")

Find Current Location

Position = F.tell ()
Print "Current file location:", Position

Reset Location

F.seek ( -3,2)

The data read is: The last 3 bytes of the file

str = F.read ()
Print "Read data is:", str

F.close ()
51cto Address http://blog.51cto.com/n1lixing

Site Link: http://www.ldxzs.top

?

Python Basics (local, global variables, functions, file operations)

Related Article

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.