Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic syntax of Python3

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces what is the basic grammar of Python3. It is very detailed and has certain reference value. Friends who are interested must finish it!

Coding

By default, Python 3 source files are encoded in UTF-8, and all strings are unicode strings. Of course, you can also specify different encodings for the source files:

#-*-coding: cp-1252-*-

The above definition allows the use of character encodings in the Windows-1252 character set in the source file, and the corresponding languages are Bulgarian, Blanc, 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, you can use Chinese as the variable name, 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 outputs all keywords for 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' Notes on 'or',' pass', 'raise',' return', 'try',' while', 'with',' yield']

Single-line comments in Python begin with #. 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 is as follows:

Hello, Python!

Multiple # signs can be used for multiline comments, as well as''and'':

Instance (Python 3.0 +)

#! / usr/bin/python3# first comment # second comment''third comment fourth''"" fifth note sixth comment "" print ("Hello, Python!")

Execute the above code, and the output is as follows:

Hello, Python!

Line and indent

The most distinctive feature of python is the use of indentation to represent blocks of code without the need for curly braces {}.

The number of indented spaces is variable, but statements of 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")

The inconsistency in the number of spaces indented in the last line of the following code results in a run error:

Example

If True: print ("Answer") print ("True") else: print ("Answer") print ("False") # indentation is inconsistent, resulting in a run error

Due to indentation inconsistencies in the above programs, errors similar to the following will occur after execution:

File "test.py", line 6

Print ("False") # indentation is inconsistent, resulting in a run error ^

IndentationError: unindent does not match any outer indentation level

Multiline statement

Python usually completes a statement in one line, but if the statement is long, we can use a backslash\ to implement multiple lines, for example:

Total = item_one +\ item_two +\ item_three

For multiline statements in [], {}, or (), you do not need to use a backslash\, for example:

Total = ['item_one',' item_two', 'item_three',' item_four', 'item_five'] numeric (Number) type

There are four types of numbers in python: integer, Boolean, floating-point, and plural.

Int (integers), such as 1, have only one integer type, int, which is represented as a long integer, and there is no Long in python2.

Bool (Boolean) such as True.

Float (floating point numbers), such as 1.23, 3E-2

Complex (plural), such as 1 + 2J, 1.1 + 2.2j

String (String)

Single and double quotation marks are used exactly the same in python.

Use three quotation marks (''or "') to specify a multiline string.

Escape character\

The backslash can be used to escape, and r can be used to prevent the backslash from escaping. If r "this is a line with\ n",\ nwill be displayed, not a line break.

Literally concatenating strings, such as "this", "is" and "string" are 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, and a character is a string of length 1.

The syntax format for intercepting a string is as follows: variable [header subscript: tail subscript: step size]

Word = 'string' sentence = "this is a sentence." paragraph = "" this is a paragraph and can be made up of multiple lines "".

Instance (Python 3.0 +)

#! / usr/bin/python3str='123456789'print (str) # output string print (str[ 0:-1]) # output all characters from the first to the last print (str [0]) # output string first character print (str [2:5]) # output from the third to the fifth Character print (str2:) # output all characters from the third start print (str1: 5:2]) # output from the second to the fifth and every other character (step 2) print (str * 2) # output string twice print (str + 'Hello') # connection character The string print ('- -') print ('hello\ nrunoob') # uses a backslash (\) + n to escape the special character print (r'hello\ nrunoob') # and adds an r before the string Represents the original string and does not escape

R here refers to raw, that is, raw string, which automatically escapes the backslash, for example:

> print ('\ n') # output blank line > print (r'\ n') # output\ n\ n >

The output result of the above example:

123456789

12345678

one

three hundred and forty five

3456789

twenty-four

123456789123456789

123456789. Hello.

-

Hello

Runoob

Hello\ nrunoob

Blank line

Functions or methods of a class are separated by blank lines to indicate the beginning of a new piece of code. The class and the function entry are also separated by a blank line to highlight the beginning of the function entry.

Blank lines, unlike code indentation, are not part of the Python syntax. No blank lines are inserted when writing, and the Python interpreter runs without error. However, the function of blank lines is to separate two pieces of code with different functions or meanings, which is convenient for future code maintenance or refactoring.

Remember: blank lines are also part of the program code.

Waiting for user input

Execute the following program to wait for user input after pressing the enter key:

Instance (Python 3.0 +)

#! / usr/bin/python3input ("\ n\ nPress the enter key and exit.")

In the above code, "\ n\ n" outputs two new blank lines before the result is output. Once the user presses the enter key, the program exits.

Display multiple statements on the same line

Python can use multiple statements on the same line, using semicolons between statements; split, here is a simple example:

Instance (Python 3.0 +)

#! / usr/bin/python3import sys; x = 'runoob'; sys.stdout.write (x +'\ n')

Execute the above code using a script, and the output is as follows:

Runoob

Execute using the interactive command line, and the output is:

> import sys; x = 'runoob'; sys.stdout.write (x +'\ n')

Runoob

seven

The 7 here represents the number of characters.

Multiple statements form a code group

Indent the same set of statements to form a code block, which we call a code group.

In compound statements such as if, while, def, and class, the first line begins with a keyword and ends with a colon (:), and one or more lines of code after that line form a code group.

We call the first line and the following code group a clause (clause).

The following is an example:

> import sys; x = 'runoob'; sys.stdout.write (x +'\ n') runoob7print output

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

Instance (Python 3.0 +)

#! / usr/bin/python3x= "a" y = "b" # Line feed output print (x) print (y) print ('-') # No line wrap output print (x, end= "") print (y, end= "") print ()

The execution result of the above example is:

A

B

-

A b

Import and from...import

Import the corresponding module in python using import or from...import.

Import the entire module (somemodule) in the format: import somemodule

Import a function from a module in the format: from somemodule import somefunction

Import multiple functions from a module in the format: from somemodule import firstfunc, secondfunc, thirdfunc

Import all functions in a module in the format: from somemodule import *

Import sys Modul

Import sysprint ('= Python import mode==') print ('command line parameter is:') for i in sys.argv: print (I) print ('\ n python path is', sys.path)

Import argv,path members of the sys module

From sys import argv,path # Import specific member print ('= python from import==') print ('path:',path) # because path members have been imported, no sys.path command line argument is required when referencing here

Many programs can perform some operations to view some basic information, and Python can use the-h parameter to view parameter help information:

$python-husage: 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 accept the parameters entered by the command line. For specific use, please refer to the Python 3 command line parameters.

The above is all the content of this article "what are the basic grammars of Python3?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report