Skip to content

Python Basic Syntax

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

Let’s explore executing Python code in different modes.

Running the python command (or python3 depending on your system) without a script file starts the interactive interpreter (Read-Eval-Print Loop):

Terminal window
$ python3
Python 3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

You can type Python commands directly at the >>> prompt and press Enter to see the result:

>>> print("Hello, Python!")
Hello, Python!
>>> 2 + 3
5
>>>

Note: Modern Python (Python 3) requires parentheses for the print function: print(...).

You can write your Python code in a file (conventionally with a .py extension) and execute it using the interpreter.

Create a file named hello.py with the following content:

hello.py
print("Hello from the script!")
message = "Python is fun"
print(message)

Run the script from your terminal:

Terminal window
$ python3 hello.py

This produces the output:

Hello from the script!
Python is fun

On Linux/macOS, you can make the script directly executable:

Add a ‘shebang’ line at the very top of hello.py specifying the interpreter:

hello.py
#!/usr/bin/env python3
print("Hello from the executable script!")
message = "Python is versatile"
print(message)

Make the file executable and run it:

Terminal window
$ chmod +x hello.py
$ ./hello.py

This produces:

Hello from the executable script!
Python is versatile

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

Punctuation like @, $, % is not allowed.

Naming Conventions (PEP 8 Style Guide):

These words have special meaning in Python and cannot be used as identifiers. All keywords are lowercase (except True, False, and None).

| False | await | else | import | pass | | None | break | except | in | raise | | True | class | finally | is | return | | and | continue | for | lambda | try | | as | def | from | nonlocal | while | | assert | del | global | not | with | | async | elif | if | or | yield |

Python uses indentation (whitespace at the beginning of a line) to define code blocks (suites) instead of braces {} used in many other languages. This is a strict requirement.

The standard and strongly recommended indentation is 4 spaces per level.

weather = "sunny"
if weather == "sunny":
print("Wear sunglasses!") # Indented block for if statement
print("Enjoy the day!") # Same indentation level
else:
print("Bring an umbrella.") # Indented block for else statement
print("Have a good day regardless.") # Back to the outer indentation level

Incorrect indentation will cause an IndentationError:

# Incorrect indentation - raises IndentationError
if True:
print("Answer")
print("True") # Error: unindent does not match any outer indentation level

Statements usually end with a newline. You can continue a statement onto the next line using the line continuation character (\):

total = 10 + \
20 + \
30
print(total) # Output: 60

Line continuation is implicitly allowed inside parentheses (), square brackets [], and curly braces {}:

weekdays = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
options = {
'color': 'blue',
'size': 'large',
'quantity': 5
}
result = (1 + 2 + 3 +
4 + 5 + 6)

Python uses single ('), double ("), and triple (''' or """) quotes for string literals. Single and double quotes work identically. Triple quotes allow strings to span multiple lines and are often used for docstrings.

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph.
It is made up of multiple lines
and sentences.
"""
alt_paragraph = '''Another way
to write multi-line
strings.'''
print(word)
print(sentence)
print(paragraph)

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

# This is a full-line comment
print("Hello, World!") # This is an inline comment
# Use comments to explain code or disable lines temporarily
# print("This line won't execute")
# Multi-line comments are typically done
# using multiple single-line comments.

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

The built-in input() function pauses program execution and waits for the user to type something and press Enter. It always returns the user’s input as a string.

name = input("Please enter your name: ")
print(f"Hello, {name}!")
# If you need a number, convert the input string
age_str = input("Enter your age: ")
try:
age = int(age_str)
print(f"You will be {age + 1} next year.")
except ValueError:
print("Invalid age entered. Please enter a number.")
# Simple pause prompt (Python 2 used raw_input)
input("\nPress Enter key to exit.")

You can place multiple statements on one line separated by a semicolon (;). This is generally discouraged by style guides (like PEP 8) as it reduces readability, but it is valid syntax.

x = 5; y = 10; print(x + y) # Less readable

A group of statements forming a code block is called a suite. Compound statements like if, while, def, class consist of a header line ending with a colon (:) followed by an indented suite.

# Example structure
if expression:
# Suite for the if block
statement1
statement2
elif another_expression:
# Suite for the elif block
statement3
else:
# Suite for the else block
statement4

Python scripts can receive arguments passed to them on the command line. These are available through the sys.argv list (you need to import sys). sys.argv[0] is the script name itself, and subsequent elements are the arguments.

For more robust command-line argument parsing, the standard argparse module is highly recommended over manually processing sys.argv.

# 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 received: {sys.argv[1:]}")
else:
print("No arguments provided.")
# Run like: python3 args_test.py first_arg 123 --option