[introduction to zero basics of Python] basic grammar of Python -- a quick overview of common basic grammar of Python

📢 preface

  • This article is a series of articles on "Python zero foundation to introduction column"
  • Python column portal here: https://blog.csdn.net/zhangay1998/category_11086734.html
  • This article provides a quick overview of Python's common basic syntax, which is also a necessary operation on the way to python~
  • Tip: the environment configuration of this article is the development environment of Python 3, and the subsequent tutorials are also Python 3

👑 A quick overview of common basic Python 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 in the alphabet or an underscore.

  • 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:

example(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 ""

example(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:

example(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:

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

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.
  • You can specify a multiline string using three quotation marks ('' or "" "").
  • 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 = 'character string'
sentence = "This is a sentence."
paragraph = """This is a paragraph,
Can consist of multiple lines"""
example(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:

example(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; Segmentation, the following is a simple example

example(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

The default output of print is newline. If you want to realize no newline, you need to add end = "" at the end of the variable:

example(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

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 modular
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 sys Modular argv,path member
from sys import argv,path  #  Import specific members
 
print('================python from import===================================')
print('path:',path) # Because the path member has been imported, sys.path is not required for reference here

🏳️‍🌈 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

👥 summary

  • Because I want to make a complete collection of Python's basic syntax to briefly introduce the commonly used syntax in Python
  • Just when the rookie saw this tutorial, he thought it was very in line with my idea, so he reprinted this article for learning
  • Thank you for your newbie ~ original link: https://www.runoob.com/python3/python3-basic-syntax.html

Tags: Python Back-end

Posted on Fri, 12 Nov 2021 09:47:52 -0500 by _DarkLink_