Skip to content

Python 3 - Basic Syntax

Python’s syntax shares some similarities with languages like Perl, C, and Java, but it has distinct features, particularly its use of indentation for code structure.

You can interact with Python in two main ways:

Start the Python interpreter by typing python or python3 in your terminal. You’ll see a prompt (usually >>>), where you can type Python code and see immediate results. This is often called a REPL (Read-Evaluate-Print Loop).

$ python3
Python 3.9.7 (...) [Clang 13.0.0 (...)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, Interactive Python!")
Hello, Interactive Python!
>>> 2 + 3
5
>>> exit() # or quit() or Ctrl-D to exit

Note: In Python 3, print is a function and requires parentheses (). Python 2 used print as a statement.

Write your Python code in a file with a .py extension (e.g., hello.py). Then, run the file using the interpreter from your terminal.

Create hello.py with this content:

hello.py
print("Hello from a Python script!")

Run it from the terminal:

$ python3 hello.py
Hello from a Python script!

On Linux/macOS, you can make the script directly executable. Add a ‘shebang’ line at the top pointing to the interpreter, make the file executable, and run it:

Modify hello.py:

hello.py
#!/usr/bin/env python3
print("Hello from an executable Python script!")

Run from the terminal:

$ chmod +x hello.py # Make executable
$ ./hello.py # Run directly
Hello from an executable Python script!

(Using #!/usr/bin/env python3 is generally preferred over hardcoding /usr/bin/python3 as it finds the python3 interpreter in the user’s environment path.)

An identifier is a name used for variables, functions, classes, modules, etc.

  • Must start with a letter (a-z, A-Z) or an underscore (_).
  • Can be followed by zero or more letters, underscores, and digits (0-9).
  • Cannot contain punctuation like @, $, %.
  • Case-sensitive: myVariable and myvariable are different.
  • Cannot be a reserved keyword (see below).

Common Naming Conventions (PEP 8 Style Guide):

  • Variables, functions, modules: lowercase_with_underscores (snake_case).
  • Classes: CapitalizedWords (CamelCase or PascalCase).
  • Constants: ALL_CAPS_WITH_UNDERSCORES.
  • Private identifiers (by convention): start with a single underscore (_private_var).
  • Strongly private (mangled): start with double underscores (__mangled_var).
  • Special language-defined names: start and end with double underscores (__init__, __name__).

These words have special meaning in Python and cannot be used as identifiers. They are always lowercase.

Falseawaitelseimport
Nonebreakexceptin
Trueclassfinallyis
andcontinueforlambda
asdeffromnonlocal
assertdelglobalnot
asyncelififor

Python uses indentation (whitespace at the beginning of a line) to define code blocks (suites) instead of curly braces {} like many other languages. This is a core feature and is strictly enforced.

The standard convention (PEP 8) is to use 4 spaces per indentation level. All statements within the same block must have the same indentation.

# Correct indentation
if True:
print("Inside the if block") # 4 spaces indent
x = 10 # Also 4 spaces
if x > 5:
print("Inside nested if") # 8 spaces indent
else:
print("Inside the else block") # 4 spaces indent
print("Outside all blocks") # No indent

Incorrect indentation will cause an IndentationError:

# Incorrect indentation - Generates IndentationError
if True:
print("Answer is True")
print("This line has wrong indentation") # Error!

Python statements usually end at the end of a line. To continue a statement onto the next line, you can use the line continuation character \ (backslash).

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

Statements within parentheses (), square brackets [], or curly braces {} can be split across multiple lines without needing the backslash.

days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
player_stats = {'name': 'Alice', 'score': 100,
'level': 5}

Python accepts single quotes ('...'), double quotes ("..."), and triple quotes ('''...''' or """...""") to denote string literals.

  • Single and double quotes work identically. Choose one and use it consistently.
  • Triple quotes allow strings to span multiple lines naturally and are often used for docstrings.
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph.
It spans multiple lines.
"""
paragraph_alt = '''Another multi-line
string using single triple quotes.'''
print(paragraph)

Use the hash sign (#) to start a comment. Everything from the # to the end of the line is ignored by the interpreter.

# This is a full-line comment
name = "Alice" # This is an inline comment explaining the variable
# Comments are used to explain code or temporarily disable it
# print("This line won't execute")

Python doesn’t have a specific syntax for multi-line block comments like /* ... */ in C/Java. To comment out multiple lines, prefix each line with #.

(Triple-quoted strings not assigned to a variable are sometimes used as block comments, but they are technically string literals that get ignored unless they are the first statement in a module/function/class, where they become docstrings.)

Blank lines (containing only whitespace or comments) are ignored by the interpreter but are used to improve code readability by separating logical blocks.

You can put multiple statements on one line separated by semicolons (;). However, this is generally discouraged by style guides (PEP 8) as it reduces readability.

x = 5; y = 10; print(x + y) # Works, but often less clear than separate lines

A group of statements executed as a unit is called a suite or block. In Python, suites are defined by indentation following a statement ending in a colon (:), such as if, while, for, def, class.

if x > 0:
# Start of the 'if' suite (indented)
print("x is positive")
y = x * 2
# End of the 'if' suite
elif x == 0:
# Start of the 'elif' suite
print("x is zero")
# End of the 'elif' suite
else:
# Start of the 'else' suite
print("x is negative")
# End of the 'else' suite
# This statement is outside the if/elif/else structure

Python scripts can accept arguments passed from the command line. The standard way to handle these in modern Python is using the argparse module from the standard library.

A simpler (but less robust) way is to access sys.argv (after import sys). sys.argv is a list where the first element (sys.argv[0]) is the script name, and subsequent elements are the arguments passed.

# Example using sys.argv (save as args_test.py)
import sys
print(f"Script name: {sys.argv[0]}")
if len(sys.argv) > 1:
print(f"Arguments passed: {sys.argv[1:]}")
else:
print("No arguments provided.")
# Run like: python3 args_test.py arg1 100 --option

(For anything beyond simple cases, learning argparse is recommended.)