Python basic syntax

Source: Internet
Author: User
Tags python list

variable naming rules:
    • The first character must be a letter in the alphabet or an underscore ' _ '.
    • The other parts of the identifier are composed of letters, numbers, and underscores.
    • Identifiers are case sensitive.
    • It can't be Chinese.
Variable naming style camel-type, underline. In Python, the use of underscores is typically named in Python 3, and non--ascii identifiers are also allowed.
 imported from XXX import * ; a __foo that begins with a double underscore represents a private member of a class; A __foo__ that begins and ends with a double underscore represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a class. 

Python reserved characters
All Python keywords contain only lowercase letters. Note that, since Python2.2, Python automatically converts integer data to long integers if an integer overflows, so it does not cause any serious consequences if you do not add the letter L after long integer data. Note: There is no longer a long type in Python3, all int

How to determine the data type:

Print (100,type (100)),
Print (' + ', type (' 100 ')) string converted to a number: Int (str) Condition: STR must be a numeric constituent number converted to a string: str (int) string: Str,python all quoted in quotation marks are strings.
Strings can be added (stitched), not subtracted, and multiplied by numbers (str*int). BOOL: Boolean value. True, false single-line comment: #多行注释: (can use 3 single quotes, or 3 double quotes) "
Third note
Iv. notes
‘‘‘

"""
Comment Five
Comment "" "code block:do not use {} curly braces. Use indentation to represent a block of code. The number of spaces indented is mutable, but the statement of the same block must contain the same number of indent spaces
If True:    print ("True") Else:    print ("False")

The following code does not match the number of spaces in the last line of the statement, resulting in a run error:

if true:    print ("Answer")    print ("true" )Else:    print ("Answer")  print (  "False")    # indentation inconsistent, resulting in a run error

The above program is not consistent due to indentation, after execution will appear similar to the following error:

File "test.py", line 6
Print ("False") # indentation is inconsistent, resulting in a run error
^indentationerror:unindent does not match no outer indentation level
The closing sentence does not require a semicolon: after the colon, the carriage return automatically indents the TAB key is meaningful, not only the code indentation, indentation inside belongs to the same logical module in the non-logical hierarchy of the code before the use of Space, TAB key. The variable does not require a specified type and is automatically converted. Python has no " variable ", only " name ". Variables are mutable, and variables need to be assigned before they are used.

#前后必须使用同样的单引号或双引号, the characters must be half-width in English. Print (' 5 ' + "8")
Above the '5'  "5 '  It's wrong

#反斜杠可以作为转义字符串, the original string is preceded by the string R, and the # Crosses multiple lines of string at the end of the #: Sanchong quoted string (can be three single quotes or three double quotes), put the content in the middle, can be used as a multiline comment print ( ‘c:\\now I\‘am‘ ) print ( ‘‘‘ line1 line3 ‘‘‘ ) print ( "hello\n" * 3 #会打印3次One feature of Python is that code blocks are not delimited by curly braces {}
Try finally no catch function
Python Empty Line

A blank line separates between functions or methods of a class, representing the beginning of a new piece of code. The class and function entries are also separated by a line of blank lines to highlight the beginning of the function entry.

Blank lines are different from code indentation, and empty lines are not part of the Python syntax. When you write without inserting a blank line, the Python interpreter runs without errors. However, the purpose of a blank line is to separate the code of two different functions or meanings, which facilitates the maintenance or refactoring of future code.

Remember: Blank lines are also part of your program code. Show multiple statements on the same line Python can use multiple statements in the same row, using semicolons between statements (;) split Print output print the default output is line wrapping, if you want to implement a non-breaking line need to add a comma at the end of the variable, x= "a"
Y= "B" # newline output print X
Print Y

print '---------' # does not wrap output print x,print y,

# no Line break output print X, y

The result of the above instance execution is:

A
B
---------
A B a B get command line arguments
Import Sysprint SYS.ARGV

SYS.ARGV used to get command line arguments

Run the command and execute the result:

./test.py hello['./test.py ', ' hello ']
Sys.argv[0] represents the path to the file itself, with parameters starting with sys.argv[1] Data Type Variable Type

Based on the data type of the variable, the interpreter allocates the specified memory and determines what data can be stored in memory.

Therefore, variables can specify different data types, which can store integers, decimals, or characters. Variables are created in memory and include information about the identity, name, and data of the variable. Variables must be assigned before they are used, and the variable will not be created until the variable is assigned.

Python has five standard data types:

    • Numbers (digital)
    • String (String)
    • List (lists)
    • Tuple (tuple)
    • Dictionary (dictionary)
Numeric data types are used to store numeric values, which are immutable data types, which means that changing the numeric data type assigns a new object. Use the DEL statement to delete references to some objects

The syntax for the DEL statement is:

Del Var1[,var2[,var3[....,varn] []]

You can delete a reference to a single or multiple objects by using the DEL statement. For example:

Del Vardel var_a, Var_b

Python supports four different types of numbers:

int (signed integral type) Long (can also represent octal and hex) = = =Python3 There is no long type. Uniform use of intfloat(floating-point) complex (plural)
String types, similar to Java syntax list lists, tuples, dictionaries list: The elements in a composite data type list can be different types. Using the medium width [] identifier, is the most versatile composite data type of python list = [' Runoob ', 786, 2.23, ' John ', 70.2]tinylist = [123, ' John '] Print List # output full listing PRI NT List[0] # The first element of the output list print List[1:3] # output second to third element print list[2:] # Output All elements from the third start to the end of the list print tinylist * 2 # Output list two times print Li List of St + tinylist # Print Combinations

The result of the above example output:

[' Runoob ', 786, 2.23, ' John ', 70.2]
Runoob
[786, 2.23] [2.23, ' John ', 70.2] [123, ' John ', 123, ' John '] [' Runoob ', 786, 2.23, ' John ', 70.2, 123, ' John ']

A tuple is another data type, similar to a list.

The tuple is identified with a "()". The inner elements are separated by commas. However, tuples cannot be assigned two times, which is equivalent to a read-only list.

A list is an ordered collection of objects, and a dictionary is an unordered collection of objects.

The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

The dictionary is identified with "{}". A dictionary consists of an index (key) and a value corresponding to it. Data type ConversionsData built-in types are converted, data types are converted, and you only need to use the data type as a function name. These functions return a new object that represents the value of the transformation.

int (x [, Base])

Converts x to an integer, base is a binary number, and default is 10 for decimal number

An example of using the Int () method is shown below:

>>>int () # When the parameter is not passed in, get the result 00>>> int (3) 3>>> int (3.6) 3>>> int (' 12 ', 16) # If it is with the parameter base, 12 to enter as a string, 12 for the 16 binary 18>>> int (' 0xa ', +) 10>>> int (' 10 ', 8) 8

Float (x)

Convert x to a floating-point number

Complex (real [, Imag])

Create a complex number

STR (x)

Convert an object x to a string

REPR (x)

Convert an object x to an expression string

eval (str)

Used to evaluate a valid Python expression in a string and return an object

Tuple (s)

Converting a sequence s to a tuple

List (s)

Convert the sequence s to a list

Set (s)

Convert to mutable Collection

Dict (d)

Create a dictionary. D must be a sequence (key,value) tuple.

Frozenset (s)

Convert to immutable Collection

Chr (x)

Converts an integer to one character

UNICHR (x)

Converts an integer to a Unicode character

Ord (x)

Converts a character to its integer value

Hex (x)

Converts an integer to a hexadecimal string

Oct (x)

Converts an integer to an octal string

Two import semantics are different import datetime print(datetime.datetime.now())is to introduce the entire datetime package
from datetime import datetimeprint(datetime.now())
 from Import: Take the mineral water out of the car and give me the import: Give me the car .

Python basic syntax

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.