Hello, World!
First of all, it must be the most classic Hello, World!
#!/usr/bin/env python3 print("Hello, World!")
What is commented out in the first line is actually to indicate what executable program the code uses to explain. It is not used here #/ In fact, usr/bin/python3 is probably not installed in this path, so we call env to find the installation path, and then call the interpreter program under the corresponding path to complete the operation.
variable
Chinese can now be used as variable names in Python 3, and non ASC Ⅱ identifiers are also allowed. The habit is similar to C.
Reserved words:
>>> 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']
Code comments use #, '', '':
#!/usr/bin/python3 # First comment # Second note ''' Third note Fourth note ''' """ Fifth note Sixth note """ print ("Hello, Python!")
Lines and indents
Unlike C language, python uses {} instead of indenting to represent code blocks. Therefore, the statements of the same code block must contain the same number of indented spaces. If the indents are inconsistent, it will run an error.
Our usual habit is to write a statement on one line, but in python, if the statement is very long, we can use backslash \ to realize multiple statements, but the multiline statements in [], {}, () do not need to use backslash \.
data type
int type, integer. There is only one integer type in python. int represents long integer.
bool, similar to C language, True and False.
float, floating point number.
Complex, complex, 1+j.
String, string. In python, single quotation marks' and double quotation marks "are exactly the same. You can specify a multiline string by using three quotation marks'" or "". Like C language, you can use the escape symbol \. If you don't want to escape, you can use r to prevent the backslash from escaping. For example, \ n \ will be displayed instead of line breaking. Use + to concatenate characters and * operator to repeat strings. Strings in python can be indexed in two ways, starting with 0 from left to right and - 1 from right to left. Interception syntax format: variable [header subscript: tail subscript: step size].
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 in front of the string to represent the original string without escape
Code format
Functions or class methods are separated by blank lines. Although blank lines will not affect the operation of the code, they can separate two sections of code with different meanings to facilitate the maintenance or reconstruction of the code in the future. It is necessary to write multiple statements on the same line; separate.
A group of sentences indented in the same form a code block. For compound statements such as if, while, def and class, the first line starts with keywords and ends with colons (:), and one or more lines of code after this line form a code group.
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:
x="a" y="b" # Wrap output print( x ) print( y ) print('---------') # Non wrapping output print( x, end=" " ) print( y, end=" " ) print()
Conversion type
a='2.1' print(int(float(a)))
Import module
Use "import" or "from" in python Import , to import the corresponding module.
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 members of sys module
from sys import argv,path # Import specific members print('================python from import===================================') print('path:',path) # Because the path member has been imported, you do not need to add sys path
Basic data type
Variables in python do not need to be declared, but they must be assigned before use, and variables will not be created until they are assigned. Moreover, in python, variables do not have the concept of type. What we call type is the type of object in memory referred to by variables.
counter = 100 # Integer variable miles = 1000.0 # Floating point variable name = "runoob" # character string print (counter) print (miles) print (name)
It is also allowed to assign values to multiple variables at the same time in python.
a = b = c = 1 a, b, c = 1, 2, "runoob"
There are six standard data types in Python 3: number, string, list, tuple, set, and dictionary. Numbers, strings, and tuples are immutable, while lists, dictionaries, and collections are mutable.
Number
Python 3 supports int, float, bool and complex. The built-in type () function can query the function type indicated by the variable. In addition, isinstance () can also be used to judge that the type function will not consider the subclass as a parent type, but isinstance will consider the subclass as a parent type.
a, b, c, d = 20, 5.5, True, 4+3j print(type(a), type(b), type(c), type(d)) a = 111 isinstance(a, int)
You can also delete some object references using the del statement
del var1[,var2[,var3[....,varN]]] del var del var_a, var_b
Operation:
>>> 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
TIPS:
- Numerical operation division, single slash returns floating-point number, and double slash returns integer.
- In mixed operations, python converts integers to floating-point numbers.
- Complex numbers in python, a+bj, where a and b are floating-point.
String
Strings in python are enclosed with 'or', and special characters are escaped with backslash. For a string, 0 is the starting value and - 1 is the starting position at the end.
TIPS:
- The backslash can be used to escape, and the use of r can prevent the backslash from escaping.
- String concatenation + reuse *.
- Strings in python cannot be changed.
List
The list can complete the data structure implementation of most geometric classes. The element types in the list can be different. It supports numbers, and strings can even contain lists (that is, nesting). List is a list of elements written between [] and separated by. Like strings, lists can also be indexed and intercepted. After being intercepted, a new list containing the required elements is returned.
list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ] tinylist = [123, 'runoob'] print (list) # Output complete 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
Unlike the string, the elements in the List can be changed, and there are many built-in methods, such as append (), pop (), and so on.
Flip string:
def reverseWords(input): # The string separator is separated by a space to separate each word into a list 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)
Tuple
Tuples are similar to lists, except that the elements of tuples cannot be modified. Tuples are written in parentheses (), elements are separated by commas, and the element types in tuples can also be different.
tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2 ) tinytuple = (123, 'runoob') print (tuple) # Output complete 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
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, and the string can be regarded as a special tuple.
Set
A set is composed of one or several large and small entities with different forms. 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 curly braces {} or the set() function to create a set. To create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.
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 set 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
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. The key must be of immutable type. In the same dictionary, the key must be unique.
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 the value of 2 print (tinydict) # Output complete dictionary print (tinydict.keys()) # Output all keys print (tinydict.values()) # Output all values
Data type conversion
python can automatically convert one data type to another without intervention. For example, when two different data types are calculated, the lower data type will be converted to the higher data type to avoid data loss.
However, types that cannot be directly operated cannot be implicitly converted, and functions need to be used for type conversion.