Python 3 basic syntax
code
By default, Python 3 source files are encoded in UTF-8, and all strings are unicode strings. Of course, you can also specify different codes for the source file:
# -*- coding: cp-1252 -*-
The above definition allows the character encoding in the Windows-1252 character set to be used in the source file, and the corresponding suitable languages are Bulgarian, Belarusian, Macedonian, Russian and Serbian.
identifier
- The first character must be a letter or underscore in the alphabet_ .
- The rest of the identifier consists of letters, numbers, and underscores.
- Identifiers are case sensitive.
In Python 3, Chinese can be used as variable names, and non ASCII identifiers are also allowed.
python reserved word
Reserved words are keywords and we cannot use them as any identifier name. Python's standard library provides a keyword module that can output all keywords of the current version:
>>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
notes
In Python, a single line comment starts with # and the examples are as follows:
Instance (Python 3.0 +)
#!/usr/bin/python3 # First comment print ("Hello, Python!") # Second comment
Execute the above code and the output result is:
Hello, Python!
Multiline comments can use multiple # numbers, as well as' 'and' ':
Instance (Python 3.0 +)
#!/usr/bin/python3 # First comment # Second comment ''' Third note Fourth note ''' """ Fifth note Sixth note """ print ("Hello, Python!")
Execute the above code and the output result is:
Hello, Python!
Lines and indents
The most distinctive feature of python is that it uses indentation to represent code blocks without curly braces {}.
The number of indented spaces is variable, but statements in the same code block must contain the same number of indented spaces. Examples are as follows:
Instance (Python 3.0 +)
if True: print ("True") else: print ("False")
Inconsistent number of spaces in the indentation number of the last line of the following code will cause a running error:
example
if True: print ("Answer") print ("True") else: print ("Answer") print ("False") # Inconsistent indentation will lead to running errors
Due to the inconsistent indentation of the above procedures, the following errors will appear after execution:
File "test.py", line 6 print ("False") # Inconsistent indentation will lead to running errors ^ IndentationError: unindent does not match any outer indentation level
Multiline statement
Python usually writes a statement on one line, but if the statement is very long, we can use backslash \ to implement multi line statements, for example:
total = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five']
For multiline statements in [], {}, or (), you do not need to use backslash \, for example:
total = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five']
Number type
There are four types of numbers in python: integer, Boolean, floating-point number and complex number.
- Int (integer), such as 1. There is only one integer type int, expressed as a Long integer, without Long in Python 2.
- bool (Boolean), such as True.
- float (floating point number), such as 1.23, 3E-2
- Complex (complex), such as 1 + 2j, 1.1 + 2.2j
String (String)
- Single quotation marks and double quotation marks are used exactly the same in python.
- Use three quotation marks ('' 'or' ') to specify a multiline string.
- Escape character\
- Backslashes can be used to escape, and r can prevent backslashes from escaping.. If r"this is a line with \n", it will be displayed instead of a line break.
- Concatenate strings literally, such as "this" "is" "string" will be automatically converted to this is string.
- Strings can be concatenated with the + operator and repeated with the * operator.
- Strings in Python can be indexed in two ways, starting with 0 from left to right and - 1 from right to left.
- Strings in Python cannot be changed.
- Python does not have a separate character type. A character is a string with a length of 1.
- The syntax format of string interception is as follows: variable [header subscript: tail subscript: step size]
word = 'string' Sentence = "this is a sentence." Paragraph = "" this is a paragraph, Can consist of multiple lines ""“
Instance (Python 3.0 +)
#!/usr/bin/python3 str='123456789' print(str) # Output string print(str[0:-1]) # Output all characters from the first to the penultimate print(str[0]) # First character of output string print(str[2:5]) # Output characters from the third to the fifth print(str[2:]) # Output all characters starting from the third print(str[1:5:2]) # Output every other character from the second to the fifth (in steps of 2) print(str * 2) # Output string twice print(str + 'Hello') # Connection string print('------------------------------') print('hello\nrunoob') # Escape special characters with backslash (\) + n print(r'hello\nrunoob') # Add an r before the string to represent the original string without escape
r here refers to raw, that is, raw string, which will automatically escape the backslash, for example:
>>> print('\n') # Output blank line >>> print(r'\n') # Output \ n \n >>>
Output results of the above examples:
123456789 12345678 1 345 3456789 24 123456789123456789 123456789 hello ------------------------------ hello runoob hello\nrunoob
Blank line
Empty lines are used to separate functions or class methods, indicating the beginning of a new piece of code. The class and function entry are also separated by an empty line to highlight the beginning of the function entry.
Blank lines, unlike code indentation, are not part of Python syntax. When writing, do not insert blank lines, and the Python interpreter will run without error. However, the function of blank lines is to separate two sections of code with different functions or meanings, so as to facilitate the maintenance or reconstruction of the code in the future.
Remember: blank lines are also part of the program code.
Waiting for user input
Execute the following procedure and wait for user input after pressing enter:
Instance (Python 3.0 +)
#!/usr/bin/python3 input("\n\n Press enter Key to exit.")
In the above code, "\ n\n" will output two new blank lines before the result output. Once the user presses the enter key, the program will exit.
Multiple statements are displayed on the same line
Python can use multiple statements in the same line, and semicolons are used between statements; Split, the following is a simple example:
Instance (Python 3.0 +)
#!/usr/bin/python3 import sys; x = 'runoob'; sys.stdout.write(x + '\n')
Use the script to execute the above code, and the output result is:
runoob
Execute using the interactive command line, and the output result is:
>>> import sys; x = 'runoob'; sys.stdout.write(x + '\n') runoob 7
7 here represents the number of characters.
Multiple statements form a code group
Indenting the same set of statements constitutes a code block, which we call a code group.
For compound statements such as if, while, def and class, the first line starts with a keyword and ends with a colon (:), and one or more lines of code after this line form a code group.
We call the first line and the following code group a clause.
Examples are as follows:
if expression : suite elif expression : suite else : suite
print output
print? The default output is line feed. If you want to realize no line feed, you need to add "end =" "at the end of the variable:
Instance (Python 3.0 +)
#!/usr/bin/python3 x="a" y="b" # Wrap output print( x ) print( y ) print('---------') # No newline output print( x, end=" " ) print( y, end=" " ) print()
The execution result of the above example is:
a b --------- a b
Import and from import
In python, use , import , or , from Import , to import the corresponding module.
Import the whole module in the format of import somemodule
Import a function from a module in the format from some module import somefunction
Import multiple functions from a module. The format is: from some module import firstfunc, secondfunc, thirdffunc
Import all functions in a module in the format from some module import*
Import sys module
import sys print('================Python import mode==========================') print ('The command line parameter is:') for i in sys.argv: print (i) print ('\n python Path is',sys.path)
Import argv and path members of sys module
from sys import argv,path # imports a specific member print ('=================================================================================================') print ('path: ', path) # because the path member has been imported, sys path
Command line parameters
Many programs can perform some operations to view some basic information. Python can use the - h parameter to view the help information of each parameter:
$ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit [ etc. ]
When we execute Python in script form, we can receive the parameters input from the command line. For specific use, please refer to Python 3 command line arguments.
Python 3 basic data type
Variables in Python do not need to be declared. Each variable must be assigned before use, and the variable will not be created until it is assigned.
In Python, a variable is a variable. It has no type. What we call "type" is the type of object in memory that the variable refers to.
The equal sign (=) is used to assign values to variables.
To the left of the equal sign (=) operator is a variable name, and to the right of the equal sign (=) operator is the value stored in the variable. For example:
Instance (Python 3.0 +)
#!/usr/bin/python3 counter = 100 # Integer variable miles = 1000.0 # Floating point variable name = "runoob" # character string print (counter) print (miles) print (name)
Executing the above procedure will output the following results:
100 1000.0 runoob
Assignment of multiple variables
Python allows you to assign values to multiple variables at the same time. For example:
a = b = c = 1
In the above example, create an integer object with a value of 1, assign values from back to front, and the three variables are given the same value.
You can also specify multiple variables for multiple objects. For example:
a, b, c = 1, 2, "runoob"
In the above example, two integer objects 1 and 2 are assigned to variables a and b, and the string object "runoob" is assigned to variable c.
Standard data type
There are six standard data types in Python 3:
- Number
- String (string)
- List
- Tuple (tuple)
- Set
- Dictionary
Among the six standard data types of Python 3:
- Immutable data (3): Number, String, Tuple;
- Variable data (3): List, Dictionary, Set.
Number
Python 3 supports int, float, bool and complex (complex).
In Python 3, there is only one integer type, int, expressed as a Long integer, and there is no Long in Python 2.
Like most languages, the assignment and calculation of numeric types are intuitive.
The built-in type() function can be used to query the object type that the variable refers to.
>>> a, b, c, d = 20, 5.5, True, 4+3j >>> print(type(a), type(b), type(c), type(d)) <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
In addition, isinstance can be used to judge:
example
>>> a = 111 >>> isinstance(a, int) True >>>
isinstance differs from type in that:
- type() does not consider a subclass to be a parent type.
- isinstance() considers a subclass to be a parent type.
>>> class A: ... pass ... >>> class B(A): ... pass ... >>> isinstance(A(), A) True >>> type(A()) == A True >>> isinstance(B(), A) True >>> type(B()) == A False
Note: in Python 3, bool is a subclass of int. True and False can be added to numbers. If True==1, False==0 , it will return , True, but you can judge the type by , is , instead.
>>> issubclass(bool, int) True >>> True==1 True >>> False==0 True >>> True+1 2 >>> False+1 1 >>> 1 is True False >>> 0 is False False
There is no Boolean in Python 2. It uses the number 0 to represent False and 1 to represent True.
When you specify a value, the Number object will be created:
var1 = 1 var2 = 10
You can also delete some object references using the del statement.
The syntax of del statement is:
del var1[,var2[,var3[....,varN]]]
You can delete one or more objects by using the del statement. For example:
del var del var_a, var_b
Numerical operation
example
>>> 5 + 4 # addition 9 >>> 4.3 - 2 # subtraction 2.3 >>> 3 * 7 # multiplication 21 >>> 2 / 4 # Divide to get a floating point number 0.5 >>> 2 // 4 # division to get an integer 0 >>> 17 % 3 # Surplus 2 >>> 2 ** 5 # Power 32
be careful:
- 1. Python can assign values to multiple variables at the same time, such as a, b = 1, 2.
- 2. A variable can be assigned to different types of objects.
- 3. The division of a number contains two operators: / returns a floating-point number and / / returns an integer.
- 4. In mixed computation, Python converts integers to floating-point numbers.
Numeric type instance
int | float | complex |
---|---|---|
10 | 0.0 | 3.14j |
100 | 15.20 | 45.j |
-786 | -21.9 | 9.322e-36j |
080 | 32.3e+18 | .876j |
-0490 | -90. | -.6545+0J |
-0x260 | -32.54e100 | 3e+26J |
0x69 | 70.2E-12 | 4.53e-7j |
Python also supports complex numbers. Complex numbers are composed of real and imaginary parts, which can be represented by a + bj or complex(a,b). Both real part a and imaginary part B of complex numbers are floating-point
String (string)
Strings in Python are enclosed in single quotation marks' or double quotation marks, and backslashes \ are used to escape special characters.
The syntax format of string interception is as follows:
Variable [head subscript: tail subscript]
The index value starts with 0 and - 1 is the starting position from the end.
The plus sign + is the connector of the string, the asterisk * indicates the copy of the current string, and the number combined with it is the number of copies. Examples are as follows:
example
#!/usr/bin/python3 str = 'Runoob' print (str) # Output string print (str[0:-1]) # Output all characters from the first to the penultimate print (str[0]) # First character of output string print (str[2:5]) # Output characters from the third to the fifth print (str[2:]) # Output all characters starting from the third print (str * 2) # Output the string twice, or write it as print (2 * str) print (str + "TEST") # Connection string
Executing the above procedure will output the following results:
Runoob Runoo R noo noob RunoobRunoob RunoobTEST
Python uses backslash \ to escape special characters. If you don't want the backslash to escape, you can add an r in front of the string to represent the original string:
example
>>> print('Ru\noob') Ru oob >>> print(r'Ru\noob') Ru\noob >>>
In addition, the backslash (\) can be used as a continuation character to indicate that the next line is a continuation of the previous line. You can also use "" ""... "" '' or ''... '' ' Span multiple lines.
Note that Python does not have a separate character type. A character is a string of length 1.
example
>>> word = 'Python' >>> print(word[0], word[5]) P n >>> print(word[-1], word[-6]) n P
Unlike C strings, Python strings cannot be changed. Assigning a value to an index location, such as word [0] ='m 'will cause an error.
be careful:
- 1. Backslashes can be used to escape, and r can prevent backslashes from escaping.
- 2. Strings can be concatenated with the + operator and repeated with the * operator.
- 3. Strings in Python can be indexed in two ways, starting with 0 from left to right and - 1 from right to left.
- 4. Strings in Python cannot be changed.
List
List is the most frequently used data type in Python.
List can complete the data structure implementation of most collection classes. The types of elements in the list can be different. It supports numbers, and strings can even contain lists (so-called nesting).
The list is a comma separated list of elements written between square brackets [].
Like strings, lists can also be indexed and intercepted. After being intercepted, a new list containing the required elements is returned.
The syntax format of list interception is as follows:
Variable [head subscript: tail subscript]
The index value starts with - 0, - 1 - from the end.
The plus sign + is a list join operator, and the asterisk * is a repeat operation. Examples are as follows:
example
#!/usr/bin/python3 list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ] tinylist = [123, 'runoob'] print (list) # Output full list print (list[0]) # First element of output list print (list[1:3]) # Output from the second to the third element print (list[2:]) # Outputs all elements starting with the third element print (tinylist * 2) # Output list twice print (list + tinylist) # Connection list
Output results of the above examples:
['abcd', 786, 2.23, 'runoob', 70.2] abcd [786, 2.23] [2.23, 'runoob', 70.2] [123, 'runoob', 123, 'runoob'] ['abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob']
Unlike Python strings, the elements in the list can be changed:
example
>>> a = [1, 2, 3, 4, 5, 6] >>> a[0] = 9 >>> a[2:5] = [13, 14, 15] >>> a [9, 2, 13, 14, 15, 6] >>> a[2:5] = [] # Set the corresponding element value to [] >>> a [9, 2, 6]
List has many built-in methods, such as append(), pop(), and so on, which will be discussed later.
be careful:
- 1. List is written between square brackets, and elements are separated by commas.
- 2. Like strings, list s can be indexed and sliced.
- 3. List s can be spliced using the + operator.
- 4. The elements in the List can be changed.
Python list interception can receive the third parameter. The parameter is used to intercept the step size. The following examples are at the positions from index 1 to index 4 and set the step size to 2 (one position apart) to intercept the string:
If the third parameter is negative, it means reverse reading. The following example is used to flip the string:
example
def reverseWords(input): # Separate each word into a list by separating the string separator with spaces inputWords = input.split(" ") # Flip string # Suppose list = [1,2,3,4], # list[0]=1, list[1]=2, and - 1 indicates that the last element list[-1]=4 (the same as list[3]=4) # inputWords[-1::-1] has three parameters # The first parameter - 1 represents the last element # The second parameter is empty, which means moving to the end of the list # The third parameter is step size, - 1 indicates reverse inputWords=inputWords[-1::-1] # Recombine strings output = ' '.join(inputWords) return output if __name__ == "__main__": input = 'I like runoob' rw = reverseWords(input) print(rw)
The output result is:
runoob like I
Tuple (tuple)
Tuples are similar to lists, except that the elements of tuple s cannot be modified. Tuples are written in parentheses () and the elements are separated by commas.
Element types in tuples can also be different:
example
#!/usr/bin/python3 tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2 ) tinytuple = (123, 'runoob') print (tuple) # Output full tuple print (tuple[0]) # The first element of the output tuple print (tuple[1:3]) # The output starts from the second element to the third element print (tuple[2:]) # Outputs all elements starting with the third element print (tinytuple * 2) # Output tuple print (tuple + tinytuple) # Join tuple
Output results of the above examples:
('abcd', 786, 2.23, 'runoob', 70.2) abcd (786, 2.23) (2.23, 'runoob', 70.2) (123, 'runoob', 123, 'runoob') ('abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob')
Tuples are similar to strings. They can be indexed, and the subscript index starts from 0 and - 1 is the position from the end. It can also be intercepted (see above, which will not be repeated here).
In fact, a string can be regarded as a special tuple.
example
>>> tup = (1, 2, 3, 4, 5, 6) >>> print(tup[0]) 1 >>> print(tup[1:5]) (2, 3, 4, 5) >>> tup[0] = 11 # It is illegal to modify tuple elements Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>>
Although the tuple element cannot be changed, it can contain mutable objects, such as list s.
It is special to construct tuples containing 0 or 1 elements, so there are some additional syntax rules:
tup1 = () # Empty tuple tup2 = (20,) # For an element, you need to add a comma after the element
string, list, and tuple all belong to sequence.
be careful:
- 1. Like strings, elements of tuples cannot be modified.
- 2. Tuples can also be indexed and sliced in the same way.
- 3. Note the special syntax rules for constructing tuples containing 0 or 1 elements.
- 4. Tuples can also be spliced using the + operator.
Set
A set is composed of one or several large and small entities with different shapes. The things or objects constituting the set are called elements or members.
The basic function is to test membership and delete duplicate elements.
You can use braces {} or the set() function to create a set. Note: to create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.
Create format:
parame = {value01,value02,...} perhaps set(value)
example
#!/usr/bin/python3 sites = {'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'} print(sites) # Output set, duplicate elements are automatically removed # Member test if 'Runoob' in sites : print('Runoob In collection') else : print('Runoob Not in collection') # Set can perform set operations a = set('abracadabra') b = set('alacazam') print(a) print(a - b) # Difference sets of a and b print(a | b) # Union of a and b print(a & b) # Intersection of a and b print(a ^ b) # Elements in a and b that do not exist at the same time
Output results of the above examples:
{'Zhihu', 'Baidu', 'Taobao', 'Runoob', 'Google', 'Facebook'} Runoob in collection {'b', 'c', 'a', 'r', 'd'} {'r', 'b', 'd'} {'b', 'c', 'a', 'z', 'm', 'r', 'l', 'd'} {'c', 'a'} {'z', 'b', 'm', 'r', 'l', 'd'}
Dictionary
A dictionary is another very useful built-in data type in Python.
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.
A dictionary is a mapping type. The dictionary is identified by {}. It is an unordered set of {keys: values.
Keys must be of immutable type.
Keys must be unique in the same dictionary.
example
#!/usr/bin/python3 dict = {} dict['one'] = "1 - Rookie tutorial" dict[2] = "2 - Rookie tools" tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'} print (dict['one']) # The output key is the value of 'one' print (dict[2]) # The output key is a value of 2 print (tinydict) # Output complete dictionary print (tinydict.keys()) # Output all keys print (tinydict.values()) # Output all values
Output results of the above examples:
1 - rookie tutorial 2 - rookie tools {'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'} dict_keys(['name', 'code', 'site']) dict_values(['runoob', 1, 'www.runoob.com'])
The constructor dict() can build a dictionary directly from the sequence of key value pairs as follows:
example
>>> dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)]) {'Runoob': 1, 'Google': 2, 'Taobao': 3} >>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36} >>> dict(Runoob=1, Google=2, Taobao=3) {'Runoob': 1, 'Google': 2, 'Taobao': 3} >>>
In addition, dictionary types also have some built-in functions, such as clear(), keys(), values(), and so on.
be careful:
- 1. A dictionary is a mapping type whose elements are key value pairs.
- 2. Dictionary keywords must be immutable and cannot be duplicated.
- 3. Create an empty dictionary using {}.
Python data type conversion
Sometimes, we need to convert the built-in type of data. For data type conversion, you only need to use the data type as the function name.
The following built-in functions can perform conversion between data types. These functions return a new object representing the converted value.
function | describe |
---|---|
Convert x to an integer | |
Convert x to a floating point number | |
Create a complex number | |
Convert object x to string | |
Converts object x to an expression string | |
Used to evaluate a valid Python expression in a string and return an object | |
Convert sequence s to a tuple | |
Convert sequence s to a list | |
Convert to variable set | |
Create a dictionary. d must be a (key, value) tuple sequence. | |
Convert to immutable set | |
Converts an integer to a character | |
Converts a character to its integer value | |
Converts an integer to a hexadecimal string | |
Converts an integer to an octal string |