YouTip LogoYouTip

Python Basic Syntax

Python2.x Python Basic Syntax

Python language has many similarities with languages such as Perl, C and Java. However, there are also some differences.

In this chapter we will learn Python's basic syntax to enable you to quickly learn Python programming.


Interactive Programming

Interactive programming does not require creating script files, but writes code through the interactive mode of the Python interpreter.

On Linux, you just need to type the Python command in the command line to start interactive programming. The prompt window is as follows:

$ python

 Python 2.7.6 (default, Sep 9 2014,15:04:36)

[GCC 4.2.1 Compatible Apple LLVM 6.0(clang-600.0.39)] on darwin

 Type "help","copyright","credits"or"license"for more information.

>>>

On Windows, the interactive programming client has been installed when installing Python. The prompt window is as follows:

Image 1

Type the following text in the Python prompt and press Enter to see the running effect:

>>> print ("Hello, Python!")

In Python 2.7.6 version, the above example outputs as follows:

Hello, Python!

Script Programming

Start executing the script by calling the interpreter with script parameters until the script execution is completed. When the script finishes execution, the interpreter becomes invalid.

Let's write a simple Python script program. All Python files will have .py as extension. Copy the following source code into test.py file.

print ("Hello, Python!")

Here, assuming you have set up the Python interpreter PATH variable. Use the following command to run the program:

$ python test.py

Output result:

Hello, Python!

Let's try another way to execute the Python script. Modify the test.py file as shown below:

Example

#!/usr/bin/python

print("Hello, Python!")

Here, assuming your Python interpreter is in /usr/bin directory, use the following command to execute the script:

$ chmod +x test.py # Add executable permission to script file $ ./test.py

Output result:

Hello, Python!


Using Python3.x's print function in Python2.x

If you want to use Python3.x's print function in Python2.x version, you can import the __future__ package, which disables Python2.x's print statement and uses Python3.x's print function:

Example

>>>list=["a","b","c"]

>>>print list# python2.x's print statement

['a','b','c']

>>>from __future__ import print_function # Import __future__ package

>>>print list# Python2.x's print statement is disabled, using it gives error

 File "<stdin>", line 1

print list

^

SyntaxError: invalid syntax

>>>print(list)# Using Python3.x's print function

['a','b','c']

>>>

Many compatibility design features between Python3.x and Python2.x can be imported through the __future__ package.


Python Identifiers

In Python, identifiers consist of letters, numbers, and underscores.

In Python, all identifiers can include English letters, numbers and underscores (_), but cannot start with a number.

Identifiers in Python are case-sensitive.

Identifiers starting with an underscore have special meanings. Those starting with a single underscore like _foo represent class attributes that cannot be accessed directly and must be accessed through interfaces provided by the class, and cannot be imported using from xxx import *.

Those starting with double underscores like __foo represent private members of the class, while those starting and ending with double underscores like __foo__ represent special method-specific identifiers in Python, such as __init__() which represents the constructor of the class.

Python can display multiple statements on the same line, separated by semicolons ;, such as:

>>> print ('hello');print (''); hello 


Python Reserved Words

The following list shows reserved words in Python. These reserved words cannot be used as constants or variables, or any other identifier names.

All Python keywords contain only lowercase letters.

and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield


Lines and Indentation

The biggest difference when learning Python compared to other languages is that Python code blocks do not use braces {} to control classes, functions, and other logical judgments. Python's most distinctive feature is writing modules using indentation.

The number of blank spaces for indentation is variable, but all code block statements must contain the same number of blank spaces for indentation, which must be strictly enforced.

The following example uses four spaces for indentation:

Example

if True:

print("True")

else:

print("False")

The following code will execute with errors:

Example

#!/usr/bin/python

# -*- coding: UTF-8 -*-

# File name: test.py

if True:

print("Answer")

print("True")

else:

print("Answer")

# No strict indentation, will report error during execution

print("False")

Executing the above code will result in the following error message:

 File "test.py", line 11 print ("False") ^IndentationError: unindent does not match any outer indentation level

IndentationError: unindent does not match any outer indentation level error indicates that your indentation methods are inconsistent, some use tab key indentation, some use space indentation, change them to be consistent.

If it's an IndentationError: unexpected indent error, then the python compiler is telling you "Hi, buddy, there's something wrong with the format in your file, it might be a problem with tabs and spaces not aligning properly", so python is very strict about formatting requirements.

Therefore, in Python's code blocks, the same number of leading indentation spaces must be used.

It's recommended that you use a single tab character or two spaces or four spaces for each indentation level, remember not to mix them


Multiline Statements

Python statements generally use new lines as the end-of-statement marker.

However, we can use backslash () to split a statement across multiple lines, as shown below:

total = item_one +  item_two +  item_three

Statements containing [], {} or () brackets do not need to use multiline continuation characters. See the following example:

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']


Python Quotes

Python can use single quotes ( ' ), double quotes ( " ), triple quotes ( ''' or """ ) to represent strings, the beginning and end of quotes must be of the same type.

Triple quotes can consist of multiple lines, providing a quick syntax for writing multi-line text, commonly used for documentation strings, and treated as comments at specific locations in files.

word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. Contains multiple statements"""


Python Comments

Single-line comments in python start with #.

Example

#!/usr/bin/python

# -*- coding: UTF-8 -*-

# File name: test.py

# First comment

print("Hello, Python!")# Second comment

Output result:

Hello, Python!

Comments can appear at the end of statement or expression lines:

name = "" # The content here is a comment

Multiline comments in python use three single quotes ''' or three double quotes """.

Example

#!/usr/bin/python

# -*- coding: UTF-8 -*-

# File name: test.py

'''

 This is a multiline comment using single quotes.

 This is a multiline comment using single quotes.

 This is a multiline comment using single quotes.

 '''

"""

 This is a multiline comment using double quotes.

 This is a multiline comment using double quotes.

 This is a multiline comment using double quotes.

 """


Python Empty Lines

Functions or methods within classes are separated by empty lines, indicating the beginning of a new piece of code. There is also one empty line separating classes and function entries to highlight the start of function entry.

Empty lines differ from code indentation. Empty lines are not part of Python syntax. Not inserting empty lines during writing won't cause errors when the Python interpreter runs. However, the role of empty lines is to separate two pieces of code with different functions or meanings, facilitating future code maintenance or refactoring.

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


Waiting for User Input

The following program will wait for user input after execution, and exit after pressing the enter key:

#!/usr/bin/python# -*- coding: UTF-8 -*- raw_input("Press enter key to exit, any other key to display...n")

In the above code, n implements line break. Once the user presses the enter key to exit, other keys will display.


Display Multiple Statements on Same Line

Python can use multiple statements in the same line, with statements separated by semicolons (;). Here is a simple example:

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

Executing the above code, the output result is:

$ python test.py 


print Output

print default output is line feed, if you want to achieve no line feed you need to add a comma , at the end of the variable.

Example

#!/usr/bin/python

# -*- coding: UTF-8 -*-

x="a"

 y="b"

# Line feed output

print x

print y

print'---------'

# No line feed output

print x,

print y,

# No line feed output

print x,y

The above example execution result is:

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

More content reference:Python2 vs Python3 print without line break


Multiple Statements Form Code Group

A group of statements with the same indentation form a code block, which we call a code group.

Compound statements like if, while, def and class start with a keyword and end with a colon (:), and one or more lines of code after that line constitute the code group.

We call the first line and the subsequent code group a clause.

As shown in the following example:

if expression : suite elif expression : suite else : suite 


Command Line Arguments

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

$ python -h usage: python  ... [-c cmd | -m mod | file | -]  ... 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 use script form to execute Python, we can receive command line input parameters. Specific usage can refer to Python Command Line Parameters.

← Python Variable TypesPython Install β†’