Python 3 basic syntax

Keywords: Python

code

By default, Python 3 source files are   UTF-8   Encoding, 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

Single line comments in Python  #  At the beginning, examples are as follows:

#!/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  #  Number, and  '''  and   """:

#!/usr/bin/python3
 
# First comment
# Second comment
 
'''
Third note
 Fourth note
'''
 
"""
Fifth note
 Sixth note
"""
print ("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:

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:

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 a line, but if the statement is long, we can use backslashes  \  To implement multiline statements, for example:

total = item_one + \
        item_two + \
        item_three

Multiline statements in [], {}, or () do not require backslashes  \, 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   (plural), 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  """) You can specify a multiline string.
  • Escape character  \
  • The backslash can be used to escape. Use r to prevent the backslash from escaping. For example, r"this is a line with \n" will be displayed instead of line breaking.
  • 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 = 'character string'
sentence = "This is a sentence."
paragraph = """This is a paragraph,
Can consist of multiple lines"""
#!/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')      # Use backslash (\)+n Escaping Special Characters 
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

Article transferred from: Python 3 basic grammar | rookie tutorial (runoob.com)

Posted by westonlea7 on Tue, 02 Nov 2021 17:53:59 -0700