Skip to content

Python3 Basic Syntax

By default, Python3 source files use UTF-8 encoding, and all strings are Unicode strings.

You can also specify a different encoding for source files:

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

The above definition allows the use of characters from the Windows-1252 character set in the source file, corresponding to languages such as Bulgarian, Belarusian, Macedonian, Russian, and Serbian.


  • The first character must be a letter (a-z, A-Z) or an underscore _ .
  • The remaining parts of the identifier consist of letters, digits, and underscores.
  • Identifiers are case-sensitive. count and Count are different identifiers.
  • There is no hard limit on identifier length, but it is recommended to keep them concise (generally no more than 20 characters).
  • Reserved keywords are prohibited. Keywords such as if, for, class, etc., cannot be used as identifiers.

Valid identifiers:

age = 25                # Plain variable name, most common
user_name = "Alice"     # Using underscores to connect words, clear and readable
_total = 100            # Leading underscore usually indicates "internal use" or "private"
MAX_SIZE = 1024         # All uppercase usually indicates a "constant" (an unchanging value)
calculate_area()        # Function name, verb + noun
StudentInfo             # Class name, first letter capitalized (CamelCase)
__private_var           # Double leading underscore, has special meaning

Invalid identifiers:

2nd_place = "silver"    # Error: starts with a digit
user-name = "Bob"       # Error: contains a hyphen
class = "Math"          # Error: uses a keyword
$price = 9.99          # Error: contains a special character
for = "loop"           # Error: uses a keyword

Python 3 allows Unicode characters as identifiers. You can use Chinese characters as variable names, and non-ASCII identifiers are also permitted.

姓名 = "张三"  # Valid
π = 3.14159   # Valid

Testing whether an identifier is valid:

def is_valid_identifier(name):
    try:
        exec(f"{name} = None")
        return True
    except:
        return False

print(is_valid_identifier("2var"))  # False
print(is_valid_identifier("var2"))  # True

Reserved words, also known as keywords, cannot be used 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', 'async', 'await', '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']
>>>
Category Keyword Description
Logical Values True Boolean true value
False Boolean false value
None Represents null or no value
Logical Operations and Logical AND operation
or Logical OR operation
not Logical NOT operation
Conditional Control if Conditional statement
elif Else if (abbreviation of else if)
else Else branch
Loop Control for Iteration loop
while Conditional loop
break Break out of the loop
continue Skip the remainder of the current loop iteration and proceed to the next
Exception Handling try Attempt to execute a code block
except Catch exceptions
finally Code block that executes regardless of whether an exception occurs
raise Raise an exception
Function Definition def Define a function
return Return a value from a function
lambda Create an anonymous function
Classes and Objects class Define a class
del Delete an object reference
Module Import import Import a module
from Import a specific part from a module
as Create an alias for an imported module or object
Scope global Declare a global variable
nonlocal Declare a nonlocal variable (used in nested functions)
Async Programming async Declare an asynchronous function
await Wait for an asynchronous operation to complete
Other assert Assertion, used to test whether a condition is true
in Check membership
is Check object identity (whether they are the same object)
pass Empty statement, used as a placeholder
with Context manager, used for resource management
yield Return a value from a generator function

For more Python reserved keywords, see: https://www.runoob.com/python3/python3-keyword.html.


In Python, single-line comments start with #. Example:

#!/usr/bin/python3
 
# First comment
print ("Hello, Python!") # Second comment

Running the above code produces the following output:

Hello, Python!

Multi-line comments can use multiple # symbols, or ''' and """:

#!/usr/bin/python3
 
# First comment
# Second comment
 
'''
Third comment
Fourth comment
'''
 
"""
Fifth comment
Sixth comment
"""
print ("Hello, Python!")

Running the above code produces the following output:

Hello, Python!

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

The number of indentation spaces is variable, but all statements within the same code block must have the same number of indentation spaces. Example:

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

The following code has inconsistent indentation spaces on the last line, which will cause a runtime error:

if True:
    print ("Answer")
    print ("True")
else:
    print ("Answer")
  print ("False")    # Inconsistent indentation will cause a runtime error

Due to the inconsistent indentation, executing the above program will produce an error similar to:

 File "test.py", line 6
    print ("False")    # Inconsistent indentation will cause a runtime error
                                      ^
IndentationError: unindent does not match any outer indentation level

Python usually writes a complete statement on one line, but if a statement is very long, we can use the backslash \\ to implement multi-line statements. For example:

total = item_one + \
        item_two + \
        item_three
item_one = 1
item_two = 2
item_three = 3
total = item_one + \
        item_two + \
        item_three
print(total) # Output: 6

Multi-line statements inside [], {}, or () do not require a backslash \\. For example:

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

Python has four types of numbers: integers, booleans, floating-point numbers, and complex numbers.

  • int (integer), such as 1. There is only one integer type int, represented as long integers, without the Long type from Python 2.
  • bool (boolean), such as True.
  • float (floating-point number), such as 1.23, 3E-2
  • complex (complex number) - Complex numbers consist of a real part and an imaginary part, in the form a + bj, where a is the real part, b is the imaginary part, and j represents the imaginary unit. For example, 1 + 2j, 1.1 + 2.2j

  • Single quotes ' and double quotes " are used exactly the same way in Python.
  • Triple quotes (''' or """) can be used to specify a multi-line string.
  • Escape character \\
  • Backslash can be used for escaping. Using r prevents backslash escaping. For example, r"this is a line with \n" will display \n literally instead of as a newline.
  • Literal string concatenation: "this " "is " "string" is automatically converted to this is string.
  • Strings can be concatenated with the + operator and repeated with the * operator.
  • Python strings have two indexing methods: from left to right starting at 0, and from right to left starting at -1.
  • Python strings cannot be changed.
  • Python has no separate character type; a single character is simply a string of length 1.
  • String slicing: str[start:end], where start (inclusive) is the slice start index and end (exclusive) is the slice end index.
  • String slicing can include a step parameter: str[start:end:step]
word = 'string'
sentence = "This is a sentence."
paragraph = """This is a paragraph,
which can span multiple lines"""
#!/usr/bin/python3
 
str='123456789'
 
print(str)                 # Output the string
print(str[0:-1])           # Output all characters from the first to the second-to-last
print(str[0])              # Output the first character of the string
print(str[2:5])            # Output characters from the third to the sixth (exclusive)
print(str[2:])             # Output all characters from the third onward
print(str[1:5:2])          # Output from the second to the fifth character, stepping by 2
print(str * 2)             # Output the string twice
print(str + 'Hello')       # Concatenate strings
 
print('------------------------------')
 
print('hello\nrunoob')      # Use backslash (\)+n to escape special characters
print(r'hello\nrunoob')     # Add an r before the string for a raw string, no escaping

Here r stands for raw, i.e., raw string, which automatically prevents backslash escaping. For example:

>>> print('\n')       # Output a blank line

>>> print(r'\n')      # Output \n
\n
>>>

Output of the above example:

123456789
12345678
1
345
3456789
24
123456789123456789
123456789Hello
------------------------------
hello
runoob
hello\nrunoob

Blank lines are used to separate functions or methods within a class, indicating the start of a new block of code. A blank line is also used between the class and function entry to highlight the start of the function entry.

Blank lines differ from code indentation. Blank lines are not part of Python’s syntax. Omitting blank lines when writing code will not cause the Python interpreter to produce an error. However, the purpose of blank lines is to separate code blocks with different functions or meanings, making future code maintenance or refactoring easier.

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


Executing the following program will wait for user input after pressing Enter:

#!/usr/bin/python3
 
input("\n\nPress enter to exit.")

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


Python allows multiple statements on the same line, separated by semicolons ;. Here is a simple example:

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

Running the above code as a script produces:

runoob

Running in the interactive command line produces:

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

Here, 7 represents the number of characters. runoob has 6 characters, and \n represents one character, totaling 7 characters.

>>> import sys
>>> sys.stdout.write(" hi ")    # There is one space before and after hi
 hi 4

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

For compound statements like if, while, def, and class, the first line starts with a keyword and ends with a colon :. The line or lines of code after this line form the code group.

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

Example:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

The print function defaults to outputting with a newline. To output without a newline, add end="" at the end of the variable:

#!/usr/bin/python3
 
x="a"
y="b"
# Output with newline
print( x )
print( y )
 
print('---------')
# Output without newline
print( x, end=" " )
print( y, end=" " )
print()

The output of the above example:

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

More content: Python2 and Python3 print without newline


In Python, use import or from...import to import corresponding modules.

Import an entire module (somemodule): import somemodule

Import a specific function from a module: from somemodule import somefunction

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

Import all functions from a module: from somemodule import *

import sys
print('================Python import mode==========================')
print ('Command line arguments:')
for i in sys.argv:
    print (i)
print ('\n Python path:',sys.path)

Importing the argv, path members from the sys module

Section titled “Importing the argv, path members from the sys module”
from sys import argv,path  # Import specific members
 
print('================python from import===================================')
print('path:',path) # Since path member is already imported, no need to add sys.path when referencing

For more content, see: Main differences between Python import and from … import


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

$ 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 executing Python in script form, we can receive command line input parameters. For specific usage, refer to Python 3 Command Line Arguments.


Start Quiz