Python 3 - Basic Syntax
Python 3 - Basic Syntax
Section titled “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.
Your First Python Interaction
Section titled “Your First Python Interaction”You can interact with Python in two main ways:
1. Interactive Mode (REPL)
Section titled “1. Interactive Mode (REPL)”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).
$ python3Python 3.9.7 (...) [Clang 13.0.0 (...)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> print("Hello, Interactive Python!")Hello, Interactive Python!>>> 2 + 35>>> exit() # or quit() or Ctrl-D to exitNote: In Python 3, print is a function and requires parentheses (). Python 2 used print as a statement.
2. Script Mode
Section titled “2. Script Mode”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:
print("Hello from a Python script!")Run it from the terminal:
$ python3 hello.pyHello 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:
#!/usr/bin/env python3
print("Hello from an executable Python script!")Run from the terminal:
$ chmod +x hello.py # Make executable$ ./hello.py # Run directlyHello 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.)
Python Identifiers (Names)
Section titled “Python Identifiers (Names)”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:
myVariableandmyvariableare 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__).
Reserved Words (Keywords)
Section titled “Reserved Words (Keywords)”These words have special meaning in Python and cannot be used as identifiers. They are always lowercase.
False | await | else | import |
None | break | except | in |
True | class | finally | is |
and | continue | for | lambda |
as | def | from | nonlocal |
assert | del | global | not |
async | elif | if | or |
Lines and Indentation
Section titled “Lines and Indentation”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 indentationif True: print("Inside the if block") # 4 spaces indent x = 10 # Also 4 spaces if x > 5: print("Inside nested if") # 8 spaces indentelse: print("Inside the else block") # 4 spaces indent
print("Outside all blocks") # No indentIncorrect indentation will cause an IndentationError:
# Incorrect indentation - Generates IndentationErrorif True: print("Answer is True") print("This line has wrong indentation") # Error!Multi-Line Statements
Section titled “Multi-Line Statements”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 + \ 3print(total) # Output: 6Statements 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}Quotations and String Literals
Section titled “Quotations and String Literals”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-linestring using single triple quotes.'''
print(paragraph)Comments
Section titled “Comments”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
Section titled “Blank Lines”Blank lines (containing only whitespace or comments) are ignored by the interpreter but are used to improve code readability by separating logical blocks.
Multiple Statements on a Single Line
Section titled “Multiple Statements on a Single Line”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 linesCode Blocks (Suites)
Section titled “Code Blocks (Suites)”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' suiteelif x == 0: # Start of the 'elif' suite print("x is zero") # End of the 'elif' suiteelse: # Start of the 'else' suite print("x is negative") # End of the 'else' suite
# This statement is outside the if/elif/else structureCommand Line Arguments (Brief Mention)
Section titled “Command Line Arguments (Brief Mention)”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.)