Python Tutorial

Python Syntax

Understanding Python's syntax is key to writing clean and efficient code. Python's design emphasizes readability, making it easier for beginners to pick up and for experienced developers to maintain.

1. Whitespace and Indentation

Unlike many other programming languages, Python does not use semicolons (;) to separate statements. Instead, it uses whitespace and indentation to define the structure of the code. This means that the way you align your code is crucial. For example:

# Define a function to print numbers
def main():
    i = 1
    max = 10
    while i < max:
        print(i)
        i = i + 1

# Call the function
main()

Notice how there are no semicolons at the end of each line. The indentation organizes the code into blocks, making it easy to see where each block begins and ends.

2. Comments

Comments are notes in your code that explain what your code is doing. They are not executed by Python and are just there to make the code easier to understand. In Python, a single-line comment starts with a hash (#) symbol:

# This is a comment explaining the next line of code
print("Hello, World!")

3. Continuation of Statements

Sometimes, a single statement is too long to fit on one line. In Python, you can continue a statement onto the next line using a backslash (\\):

if (a == True) and (b == False) and (c == True):
    print("Continuation of statements")

4. Identifiers

Identifiers are names you give to variables, functions, classes, etc. They must start with a letter or an underscore (_) and can be followed by letters, numbers, or underscores. For example, variable1 and _myFunction are valid identifiers. Identifiers are case-sensitive, so myVariable and MyVariable are different.

5. Keywords

Keywords are reserved words in Python that have special meanings. You cannot use these as identifiers. Some examples of Python keywords include if, else, while, for, and def. To see the full list of keywords in your Python version, you can use the following code:

import keyword
print(keyword.kwlist)

6. String Literals

In Python, strings can be enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """). Triple quotes are useful for multi-line strings:

s = 'This is a string'
s = "Another string"
s = '''This string spans
multiple lines'''

Each string literal must start and end with the same type of quote.

Summary

  • Python uses whitespace and indentation to define the structure of the code.
  • Comments are used to explain code and are ignored by Python during execution.
  • Long statements can be split across multiple lines using a backslash (\\).
  • Identifiers are names for variables, functions, etc., and are case-sensitive.
  • Keywords are reserved words in Python and cannot be used as identifiers.
  • Strings can be enclosed in single, double, or triple quotes.