Python basic Syntax 1

Source: Internet
Author: User

Everything is possible---nothing is impossible

Summary: Input and output, conditions and loops, file operations, exceptions, modules and packages,python features, Linux basics and Git

1 Basic Syntax:

1: Input and output:

1, modifying immutable data will throw TypeError error

2,print calls the Sys.stdout.write method by default: Output A string to the console

3,input get user input, all strings

Python2 has raw_input,input. Input gets the type that is entered

2: The condition follows the bad:

1, there is an anonymous function--------------------------------------, 2.1

2,range and xrange The difference is: the same function, xrange only use will open up memory, good performance

3, the dictionary in the entire code block, as long as the dictionary name is the same, the values are all the same, modified similar to a shallow copy

4,range (5,0,-1): 5 4 3 2 1

3: File operations

1, read the data: Through the code to make a generator, slice read stitching. You can also use the Linux split to cut into small files in the crafting

2, the file operation of read: Read the entire file, limited by memory. ReadLine reads the next line, using the generator's method, ReadLines: reads the entire file into an iterator for us to traverse.

3, Yunyong----------------------3.4 for OS

4: Exception

The finally method is also executed after 1,except, and you can throw an exception using raise

2,except: #捕获所有异常

Except "Exception name": #捕获指定异常

Except "Exception name 1", "Exception Name 2": #捕获异常1或异常2

Except "Exception name", "Data": # captures the specified exception and its attached data

Except "Exception 1", "Exception 2", "Data": # Catch exceptions and data

5: Modules and Packages

1, 1: Common Python standard library

OS operating system

Time

Random randomly

Pymysql Linked Database

Threading Threads

Multiprocessing process

Queue queues

2 third-party libraries:

Django and Flask

Requests request

Virtualenv Virtual Environments

Selenium----------------------------don't know.

Scraoy-----------------------------don't know.

Xadmin--------------------------------don't know.

Celery Asynchronous Start Task

Re Regular

Hashlib-------------------------------don't know.

MD5--------------------------------don't know.

Common Scientific Computing libraries: Numpy,scipy,pandas

2, the difference between assignment, shallow copy and deep copy

1 Assignment: Simple object reference, different from C + + (just different name)

You can use the ID () to view the memory address of both

2 Shallow copy: Creates a new object, a reference to the first-level object of the original object

Slice operation:B = a[:] or B = [x for x in a]

Factory function:b = List (a)

copy function: b = copy.copy (a)

3 deep copy: Not only creates new objects, it opens up new memory for all objects inside. Immutable objects are references that reduce overhead (atomic type of data)

The difference between 3,__init__ and __new__

__INIT__: Initialization after object creation

__NEW__: Creates an object before the object is created and returns the object to the Init

Generate random numbers in 4,python

Import Random

Random.random (): Generates a random floating-point number between 0-1

Random.uniform (A, B): Generates a random floating-point number between a A and a

Random.randint (A, B): Generates a random integer between a A and a

Random.randrange (A, B, step): In the specified set [a, b], the base of step, the random area of a number

Random.choice (Sequence): A random area from a specific sequence of elements, elements can be strings, lists, Ganso, etc.

Random.shuffle (alist): randomly arranged list

5, using the DateTime module, determine which year of the month that day is the days of the year----5-5

1. Import datetime

2. Def dayofyear ():

3. Year = input ("Please enter years:")

4. Month = input ("Please enter month:")

5. Day = input ("Please enter Days:")

6. Date1 = Datetime.date (Year=int (year), Month=int (month), Day=int (day))

7. Date2 = Datetime.date (Year=int (year), Month=1,day=1)

8. Return (Date1-date2 + 1). Days

6, randomly arranged list: Random.shuffle (list)

The difference between 7,os.path and Sys.path

Os.path: Operations on system path files

Sys.path: Action on the system environment parameters of the Python interpreter (dynamically modifying the Interpreter search path)

Common methods for OS modules in 8,python

Os.remove (): Delete file

Os.rename (): Rename file

Os.walk (): Generate all file names under the directory tree

Os.chdir (): Change Directory

Os.mkdir/makedirs (): Create directory, multi-level directory

Os.rmdir/removedirs (): Delete directory, multi-level directory

Os.listdir (): Lists files for the specified directory

OS.GETCWD (): Get current working directory

Os.chmod (): Change directory Permissions

Os.path.basename (): Remove directory path, return file name

Os.path.dirname (): Remove file name, return directory path

Os.path.join (): Combines the parts of the separation into one path name

Os.path.split (): Return (DirName (), basename ()) tuple

Os.path.splitext (): (return filename,extension) tuple

Os.path.getatime\ctime\mtime: Returns the last access, creation, modification time, respectively

Os.path.getsize (): Return file size

Os.path.exists (): Presence

Os.path.isabs (): is an absolute path

Os.path.isdir (): Whether it is a directory

Os.path.isfile (): Whether it is a file

Common methods of 9,python in SYS

SYS.ARGV: Command line argument list, the first element is the path of the program itself

Sys.modules.keys (): Returns the list of all modules that have been imported

Sys.exc_info (): Gets the class currently being processed, Exc_type, Exc_value, Exc_traceback, exception information currently handled

Sys.exit (N): Exit program, Exit normally (0)

Sys.hexversion: Gets the version value of the Python interpreter, 16 binary format

Sys.version: Get version information for Python interpreter

Sys.maxint: the largest int value

Sys.maxunicode: Bigger Unicode value

Sys.modules: Returns the module field of the system import, key is the module name, value is the module

Sys.path: Returns the search path for the module, using the value of the PYTHONPYTH environment variable when initializing

Sys.paltform: Returns the name of the operating system platform

Sys.stdout: Standard Output

Sys.stdin: Standard input

Sys.stderr: Error Output

Sys.exc_clear (): Used to clear the current received recent error message from the current thread

Sys.exec_prefix: Returns the location of the platform standalone Python file installation

Sys.byteorder: Indicator of the local byte rule, the value of the Big-endian platform is ' big ', the value of the Little-endian platform is ' little '

Sys.copyright: Record python copyright-related stuff

Sys.api_version: API version of the interpreter C

Sys.version_info: Tuples use an easier way to make your program available in Python version requirements

What is 10,unittest?

in python, UnitTest is a unit testing framework that he has--support for shared builds, automated testing. The ability to pause code in a test, iterate over different tests into a group, etc.

11. What are modules and packages?

(1) The module is a way to build a program, each Python code file is a module, and can apply other modules, such as objects and properties

(2) a package containing many Python code folders is a package. A package can contain modules and sub-folders

6:python characteristics

1,python is a strong language or a weak language type

Python is a strongly typed, dynamic scripting language

Strong type: Do not allow different types to think home

Dynamic: Not painful display data type declaration, tangent to determine the type of a variable is the first time to assign him a value

Scripting language: Generally also interpreted language, running code requires only one interpreter, no compilation required

2, interpreted language, compiled language

Computers cannot directly understand high-level languages, they can only understand machine language directly, so it is necessary to translate high-level languages into machine-language computers to perform programs written in high-level languages

(1) Interpreted language: Translation is performed when the program is run.

(2) Compiled language: Written program before execution, need a special compilation process, the program compiled into machine language (executable file)

Logs in the 3,python

Python comes with the logging module, calls the Logging.basicconfig () method, configures the required log level and corresponding parameters, and the Python interpreter generates the corresponding log according to the configured parameters.

How 4,python is the type conversion

internally encapsulated conversion function,list-tuple tuple (list) int (str) num character

The difference between 5,python2 and Python3

(1) Core class differences

(2) Waste class differences

(3) Modifying class differences

(4) Third-party toolkit differences

(5) Tool installation problems

6,python the operation of the program, what means can improve performance

① uses multiple processes to take full advantage of the machine's multicore performance

② for some code that has a large performance impact, you can use C or C + + to write

③ for the performance impact of Io blocking, you can use IO multiplexing to solve

④ using Python's built-in functions as much as possible

⑤ use local variables as much as possible

Scopes in 7,python

The role of variables in Python is always determined in the place where the code is assigned, and the number Python encounters a variable that is searched in this order:

1 Native Scope Local

2 The current scope is embedded in the local scope enclosing locals

3 Global/Module scopes Global

4 built-in scope built-in

8, what is Python

(1) Python is a language, he has objects, modules, threads, exception handling, and automatic memory management, can be added to other language contrast

(2) Python is an interpreted language, and Python code does not need to be explained before it runs

(3) Python is a dynamic type language, and when declaring a variable, it is not necessary to describe the type of the variable

(4) Python is suitable for object-oriented change because it supports defining classes by combining and inheriting

(5) in the Python language, a function is the first class of objects.

(6) Python code is written fast, but runs slower than the compiled language

(7) Python is widely used, known as ' glue language ', to help other languages and components improve health

(8) using Python, programmers can focus on the design of algorithms and data structures without having to deal with the underlying details

9, What is the introspection of Python

Python has the ability to write programs written by the programmer's object-oriented language at run time, to get the object's class python type, Python is an interpreted language, providing programmers with great flexibility and control

What is the namespace of Python

in python, all names exist in a space, they exist and are manipulated in space-this is the namespace.

Like a box, each variable name corresponds to an object, and when the variable is queried, it looks for the object in that box.

11, what code specifications are you following?

12,PEP8 specification

(1) Variables

① constant: uppercase and underlined. Like user_constant.

② Private variables: lowercase and a leading underscore. _private_value

There is no private variable in Python, that is, the habit of not wanting to be accessed by an external class

③ built-in variables: lowercase, two leading underscores, and two post-underline. __class__

Two leading underscores cause variables to be renamed during interpretation, in order to avoid conflicts between built-in variables and other variables. User-defined variables to strictly avoid this style

(1)

(2) Functions and methods, in general, lowercase and underlined

① Private methods: lowercase and a leading underscore

This is not really a private access, as with variables, do not use double underline

② Special methods: lowercase and two leading underscores, two post-underline

This method value is applied with special functions such as operator overloading, etc.

③ function Parameters: lowercase and underscore, default (parameter) value no spaces on both sides of the equals sign

(3) Class:

the ① class is always named with the hump format, that is, all words are capitalized with the remaining lowercase letters. Thunder should be concise, precise, and sufficient to understand the work done by the class. One common method is to use a suffix that represents its type or attribute, for example:sqlengine,mimetypes Duyu accumulation, you can use a base or an abstract prefix

(4) Modules and packages

① out of the Special Envoy module __init__, the module name uses lowercase letters that are not underlined

② If they implement a protocol, LIB is usually used as a suffix, for example: import smtplib,import os,import sys

(5) About parameters

① do not use assertions to implement static type detection, assertions can be used to check parameters

② do not abuse *args and **kwargs. Will destroy the robustness of the function, it will blur the label name, and the code try to start building a small parameter parser where it should not be.

(6) Other

① uses the has or is prefix to name the Boolean element. Is_connect=true

② names a sequence in plural form. numbers=[' user_1 ', ' user_2 ']

③ names the dictionary with the display name. person_address={' user_1 ': ' Ten Road WD ', ' user_2 ': ' Street Huafu '}

④ avoid generic names. such as list,dict,sequence or element.

⑤ Avoid existing names. Names such as Os,sys, which already exist in the system, should be avoided

(7) Some numbers

① numberof rows: PEP8 79 columns, do not exceed the number of display columns of the editor when full screen

② a function: Do not exceed 30 lines of code, can be displayed in a screen class

③ A class: Do not exceed 200 lines of code, and do not have more than 10 methods.

④ A module: Do not exceed 500 lines

(8) Verification script

① can install a pep8 script to verify that your code style conforms to PEP8

7,linux Basics and Git

1,linux to differentiate between a file or a folder:

Ls-f: After file is * folder after Yes/

2, the log in what format, where to store

The log with text can be stored in the /var/log directory with the suffix named. log

3,linux viewing a service's port: NETSTAT-ANP | grep service_name

4,ubuntu setting up a program for booting from startup

① directly modifies the contents of the/ETC/RE0.D~/ETC/RC6.D and/ECT/RCS.D folders, S starts with the start, and the start of the K starts

5, the difference between find and grep in Linux

①grep is a powerful text search tool that can use regular expressions to search for text and print matching lines, and global Regular expression Print, which represents the global regular expression version, with all user permissions.

Find under ②linux:

1) Function: Search the directory structure of the file, and perform the specified action, this command provides a considerable number of search criteria, powerful.

2) syntax:Find in fact directory search criteria

3) Description:The Find command starts at the specified starting directory, recursively searches subdirectories, finds files that meet the search criteria, and takes related actions

4) Simply put,grep is the line that finds matching criteria, and find is a file that searches for matching criteria

6,linux REDIRECT command:

① redirect >:linux allows the result of the I type of the command to be redirected to a file that should be displayed on the terminal to be saved to the specified file, such as ls > test.txt (created if the file does not exist, overwrite if present)

② redirect >>: This is to append the output to the destination file. If the file does not exist, the file is created, it is appended to the end of the file, and the cause of the file is not affected

7, the difference between soft links and hard links

soft links are like shortcuts to Windows, and when you delete a source file, the soft link also fails. A hard link can be understood as an alias for the source file, and multiple aliases represent the same file. When RM is a file, the number of hard links for this file is reduced by 1, and when the number of hard links is 0 o'clock, the file is deleted

8,10 a common Linux command

①PWD: Show Work path

②ls: Viewing files in a directory

③cd/home: Enter '/home ' directory

④CD. Return to the top level directory

⑤CD. /.. Return to the top level two directory

⑥mkdir Dir1 Create a directory called Dir1

⑦rm-f file1 Delete a file called File1,-F ignores nonexistent files, does not give hints

⑧rmdir Dir1 Delete a directory called Dir1

⑨groupadd group_name Create a new user group

⑩groupdel group_name Delete a user group

? TAR-CVF Archive.tar File1 Create a non-compressed tarball

? TAR-CVF Archive.tar file1 file2 dir1 Create a file containing ' file1 ', ' file2 ' and ' Dir1 '

? TAR-TF Archive.tar Display the contents of a package

? TAR-XVF Archive.tar Release a package

? TAR-XVF ARCHIVE.TAR-C/TMP releases the compressed package into the/tmp directory

? TAR-CVFJ archive.tar.bz2 Dir1 Create a compressed package in BZIP2 format

? TAR-XVFJ archive.tar.bz2 extract a compressed package in BZIP2 format

? TAR-CVFZ archive.tar.gz Dir1 Create a zipped package in gzip format

? TAR-XVFZ archive.tar.gz Unzip a compressed package in gzip format

What are the shutdown commands for 9,linux?

Reboot restart

Shutdown-r now restarts the operating system,shutdown will prompt other users

Shutdown-h now shuts down immediately, where it is equivalent to the 0 state of time

Shutdown-h 10:25 system in today's 20.25 shutdown

Shutdown-h +10 system automatically shuts down after 10 minutes

Init 0 shutdown

Init 6 Restart

10,git merge files How do I deal with conflicts?

①git merge conflict, follow the prompts to find the conflicting file, resolve the conflict, if the file is conflicting, then there will be a similar tag

after the ② modification is complete, execute the git add conflict file name

③git Commit NOTE: There is no-m option to go into a vim-like interface and remove the conflict-related lines directly from the push, as the associated merge operation has just been performed

Python basic Syntax 1

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.