home PYTHONJAVA
 

Python3 basic syntax

Encoding

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

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

The above definition allows the use of character encoding in the Windows-1252 character set in the source file, corresponding to the Bulgarian, White, Macedonian, Russian, and Serbian languages.


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, non-ASCII identifiers are also allowed.


python reserved words

Reserved words are keywords, and we cannot use them as any identifier name. Python's standard library provides a keyword module that outputs all the keywords of the current version:

Comment

Single-line comments in Python start with #, as shown in the following example:

Instance (Python 3.0+)

#!/usr/bin/python3 # first comment print ("Hello, Python!") # second comment

Execute the above code, the output is:

Hello, Python!

Multi-line comments can have multiple # numbers, as well as ''' and """:

Instance (Python 3.0+)

#!/usr/bin/python3 # first comment # second comment ''' Third comment Fourth note ''' """ Fifth comment Sixth comment """ print ("Hello, Python!")

Execute the above code, the output is:

Hello, Python!

Lines and indents

The most distinctive feature of Python is the use of indentation to represent code blocks, without the use of braces {} .

The number of indented spaces is mutable, but statements in the same 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 number of spaces indented in the last line of the following code is inconsistent, causing a runtime error:

if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False") # 

The above program is inconsistent due to indentation, and the following error will occur after execution.:

 File "test.py", line 6
print ("False") # Inconsistent indentation can lead to runtime errors
^
IndentationError: unindent does not match any outer indentation level

Multiline statements

Python usually writes a single statement in a row, but if the statement is long, we can use a backslash (\) to implement a multi-line statement, for example:

total = item_one + \
        Item_two + \
        Item_three

Multiple lines in [], {}, or () do not require a backslash (\), for example:

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

Number type

There are four types of numbers in python: integers, booleans, floats, and complex numbers.

  • int (integer), such as 1, only one integer type int, expressed as a long integer, without a Long in python2.
  • bool (Boolean), such as True.
  • float (float), such as 1.23, 3E-2
  • complex (plural), such as 1 + 2j, 1.1 + 2.2j

String (String)

  • In python, single quotes and double quotes are used exactly the same.
  • Use three quotation marks (''' or """) to specify a multi-line string.
  • escape character '\'
  • Backslashes can be used to escape, and r can be used to escape backslashes. . If r"this is a line with \n" then \n will show, not a newline.
  • Cascading strings literally, such as "this" "is" "string" is automatically converted to this is string.
  • Strings can be joined together with the + operator and repeated with the * operator.
  • Strings in Python have two indexing methods, starting with 0 from left to right and starting with -1 from right to left.
  • Strings in Python cannot be changed.
  • Python does not have a separate character type, a character is a string of length 1.
  • The syntax of the interception of a string is as follows: variable [header subscript: tail subscript: step size]
word = 'String'
Sentence = "This is a sentence."< Span class="pln">
Paragraph = """This is a paragraph,
Can consist of multiple lines """

Instance(Python 3.0+)

#!/usr/bin/python3 str='Runoob' print(str) # Output string... print(str[0:-1]) # Output all characters from the first to the second last print(str[0]) # Output string output string first character print(str[2:5]) # Output characters from the third to the fifth print(str[2:]) # Output all characters after the third start print(str * 2) # Output string twice print(str + 'Hello there') # Connection string print('------------------------------') print('hello\nrunoob') # Use backslash (\)+n to escape special characters print(r'hello\nrunoob') # Add an r in front of the string to represent the original string, no escaping

Here r means raw, which is raw string.

The output is:

Runoob
Runoo
R
noo
noob
RunoobRunoob
RunoobHello there
------------------------------
hello
runoob
hello\nrunoob

empty line

The function or the method of the class is separated by a blank line, indicating the beginning of a new piece of code. The class and function entries are also separated by a blank line to highlight the beginning of the function entry.

A blank line is different from code indentation. A blank line is not part of the Python syntax. When you write without inserting a blank line, the Python interpreter will not go wrong. But the role of blank lines is to separate two different functions or meanings of code for future maintenance or refactoring.

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


Wait for user input

Execute the following program and wait for user input after pressing the Enter key:

Instance (Python 3.0+)

#!/usr/bin/python3 input("< Span class="hl-special">\n\nPress the enter key to exit.")

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


Show multiple statements on the same line

Python can use multiple statements on the same line, separated by semicolons (;), the following is a simple example:

Instance (Python 3.0+)

#!/usr/bin/python3 import sys; x = 'runoob'; /span>sys.stdout.write(x + '\n ')

Use the script to execute the above code, the output is:

runoob

Execute using the interactive command line, the output is:

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

The 7 here is the number of characters.


Multiple statements form a code group

Indenting the same set of statements constitutes a block of code, which we call a code group.

Composite statements like if, while, def, and class. The first line begins with a keyword and ends with a colon ( : ). One or more lines of code after the line form a code group.

We refer to the first and subsequent code groups as a clause.

Example below:

if expression :
    Suite
elif expression :
    Suite
else :
    Suite

Print output

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

Instance (Python 3.0+)

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

The above example execution result is:

a
b
---------
a b

import and from...import

Use import or from...import in python to import the appropriate module.

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 the functions in a module in the format: from somemodule import *

Import sys module

import sys print('================Python import mode=========================='); print ('The command line argument is:') for i in sys.argv: print (i) print ('\n python Path is',sys.path)

Import the argv of the sys module, path member

from sys import argv,path # Import specific members print('================python from import===================================') print('path:',path) # Since the path member has been imported, there is no need to add it when referring here.sys.path

Command line parameters

Many programs can perform some operations to view some basic information. Python can use the -h parameter to view help information for 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. ]





javacodegeeks is optimized for learning.© javacodegeeks. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.