Syntax & Basics

Learn the fundamental building blocks of Python programming

Introduction

Python's syntax is designed to be clean, readable, and intuitive. Unlike many programming languages, Python uses indentation to define code blocks rather than braces or keywords. This lesson will introduce you to the core syntax rules, basic data types, variables, and fundamental operations that form the foundation of Python programming.

Python Syntax Fundamentals

Indentation: Python's Signature Feature

Python uses indentation (whitespace) to define code blocks. This is different from languages like C++ or Java that use braces {}. Consistent indentation is not just style in Python, it's a requirement!

# Correct indentation
if True:
    print("This is indented")
    print("This too")
print("This is not indented - different block")

# Wrong - will cause an error
if True:
print("This will cause an IndentationError")

Important: Use either 4 spaces or 1 tab consistently throughout your code. Mixing spaces and tabs will cause errors. Most Python developers use 4 spaces (the PEP 8 standard).

Comments

Comments help document your code and are ignored by Python. Use them to explain what your code does:

# This is a single-line comment

# You can also write comments
# across multiple lines like this

"""
This is a multi-line string (docstring)
Often used for documentation
Can span multiple lines
"""

def my_function():
    """This is a docstring describing the function."""
    pass

Statements and Line Continuation

Python statements typically end at the end of a line. For long lines, you can use backslashes or parentheses:

# Single statement per line
x = 5
y = 10

# Multiple statements on one line (not recommended)
x = 5; y = 10

# Line continuation with backslash
total = 1 + 2 + 3 + \
        4 + 5 + 6

# Line continuation with parentheses (preferred)
total = (1 + 2 + 3 +
         4 + 5 + 6)

Variables

Variables in Python are created by simply assigning a value to a name. You don't need to declare the type, Python infers it automatically, a feature known as dynamic typing. However, because of dynamic typing, mistyped variable names or changing variable types can sometimes result in errors at runtime. Later in the course, we'll look at mechanisms and tools that help catch these issues and improve type safety in your code.

Creating Variables

# Simple assignment
name = "Alice"
age = 30
height = 5.6
is_student = True

# Multiple assignment
x, y, z = 1, 2, 3

# Same value to multiple variables
a = b = c = 0

# Variable names are case-sensitive
Name = "Bob"    # Different from 'name'
name = "Alice"  # Different from 'Name'

Naming Rules and Conventions

✓ Valid Names
  • my_variable
  • user_name
  • count123
  • _private
  • total_amount
✗ Invalid Names
  • 123count (starts with number)
  • my-variable (has hyphen)
  • class (reserved word)
  • user name (has space)
  • $amount (special character)
PEP 8 Naming Conventions
  • Variables: Use snake_case (e.g., user_name)
  • Constants: Use UPPER_SNAKE_CASE (e.g., MAX_SIZE)
  • Classes: Use PascalCase (or Camel Case) (e.g., UserAccount)

Underscores and Private Variables

In Python, the use of underscores in variable and method names has special meaning:

  • _single_leading_underscore: By convention, variables or methods starting with a single underscore (e.g., _secret) are considered internal or "private". They can still be accessed, but it signals to other programmers that they are for internal use.
  • __double_leading_underscore: Names starting with two underscores (e.g., __hidden) trigger name mangling in classes, making it harder (but not impossible) to access them from outside the class. This is used to avoid accidental overrides in subclasses, not for true privacy.
  • __double_underscores_at_ends__: Names with double underscores at both ends (e.g., __init__, __str__) are reserved for special methods (sometimes called "dunder methods"). Avoid creating such names yourself unless you're implementing Python's own special behavior.
class Example:
    def __init__(self):
        self.public = 123
        self._internal = 456       # Convention: internal use
        self.__private = 789       # Name mangled: only accessible as _Example__private

obj = Example()
print(obj.public)               # 123
print(obj._internal)            # 456 (possible, but not recommended)
# print(obj.__private)          # AttributeError!
print(obj._Example__private)    # 789 (name-mangled access)

print(obj.__class__.__name__)   # "Example"
Note: Underscores do not make variables truly private. They are a signal for proper usage, not a strict access control mechanism!

Basic Data Types

Python has several built-in data types. Let's start with the most fundamental ones:

Integers (int)

Whole numbers, positive or negative:

age = 25
count = -10
big_number = 1000000

Floats (float)

Decimal numbers:

price = 19.99
temperature = -5.5
pi = 3.14159

Strings (str)

Text data, enclosed in quotes:

name = "Alice"
message = 'Hello, World!'
multiline = """This is
a multi-line
string"""

Booleans (bool)

True or False values:

is_active = True
is_complete = False
# Note: Capital T and F

Checking Data Types

Use the type() function to check what type a variable is:

x = 42
y = 3.14
z = "Hello"
w = True

print(type(x))  # <class 'int'>
print(type(y))  # <class 'float'>
print(type(z))  # <class 'str'>
print(type(w))  # <class 'bool'>

Basic Operations

Arithmetic Operations

# Addition
result = 5 + 3        # 8

# Subtraction
result = 10 - 4       # 6

# Multiplication
result = 7 * 2        # 14

# Division (always returns float)
result = 10 / 3       # 3.333...

# Floor division (integer division)
result = 10 // 3      # 3

# Modulo (remainder)
result = 10 % 3       # 1

# Exponentiation (power)
result = 2 ** 3       # 8 (2 to the power of 3)

Comparison Operators

x = 5
y = 10

x == y   # False (equal to)
x != y   # True (not equal to)
x < y    # True (less than)
x > y    # False (greater than)
x <= y   # True (less than or equal)
x >= y   # False (greater than or equal)

Logical Operators

# and - both must be True
True and True   # True
True and False  # False

# or - at least one must be True
True or False   # True
False or False  # False

# not - inverts the value
not True        # False
not False       # True

# Practical example
age = 25
has_license = True

can_drive = age >= 18 and has_license  # True

String Operations

String Concatenation and Repetition

# Concatenation (joining strings)
first = "Hello"
last = "World"
greeting = first + " " + last  # "Hello World"

# Repetition
stars = "*" * 5  # "*****"
line = "-" * 20  # "--------------------"

# String formatting (f-strings - Python 3.6+)
name = "Alice"
age = 30
message = f"My name is {name} and I'm {age} years old"
# "My name is Alice and I'm 30 years old"

# Older formatting methods
message = "My name is {} and I'm {} years old".format(name, age)
message = "My name is %s and I'm %d years old" % (name, age)

Common String Methods

text = "  Hello, World!  "

text.upper()        # "  HELLO, WORLD!  "
text.lower()        # "  hello, world!  "
text.strip()        # "Hello, World!" (removes whitespace)
text.replace("World", "Python")  # "  Hello, Python!  "
text.split(",")     # ['  Hello', ' World!  ']
len(text)           # 17 (length of string)

# Check if string contains substring
"Hello" in text     # True
"Python" in text    # False

Type Conversion

Sometimes you need to convert values from one type to another. Python provides built-in functions for this:

# Converting to integer
int("42")        # 42
int(3.14)        # 3 (truncates decimal)
int(True)        # 1
int(False)       # 0

# Converting to float
float("3.14")    # 3.14
float(42)        # 42.0
float(True)      # 1.0

# Converting to string
str(42)          # "42"
str(3.14)        # "3.14"
str(True)        # "True"

# Converting to boolean
bool(1)          # True
bool(0)          # False
bool("")         # False (empty string)
bool("Hello")    # True (non-empty string)
bool([])         # False (empty list)
bool([1, 2])     # True (non-empty list)

# Common use case: user input
age = input("Enter your age: ")  # Returns string
age = int(age)  # Convert to integer

Input and Output

Printing Output

# Basic print
print("Hello, World!")

# Print multiple items
print("Hello", "World", "!")  # Hello World !

# Print with separator
print("Hello", "World", sep="-")  # Hello-World

# Print without newline
print("Hello", end="")
print("World")  # HelloWorld

# Print with formatting
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")  # Name: Alice, Age: 30

Getting User Input

# Get string input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Get numeric input (remember to convert!)
age = input("Enter your age: ")
age = int(age)  # Convert string to integer
print(f"You are {age} years old")

# One-liner conversion
age = int(input("Enter your age: "))

Remember: input() always returns a string. If you need a number, you must convert it using int() or float().

Putting It All Together

Here's a simple example that demonstrates many of the concepts we've covered:

# Simple calculator program
print("=== Simple Calculator ===")

# Get user input
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

# Perform calculation
if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    if num2 != 0:
        result = num1 / num2
    else:
        print("Error: Division by zero!")
        result = None
else:
    print("Error: Invalid operator!")
    result = None

# Display result
if result is not None:
    print(f"\nResult: {num1} {operator} {num2} = {result}")

Key Takeaways

Syntax Rules

  • Indentation defines code blocks (use 4 spaces)
  • Comments start with # or use triple quotes
  • Statements end at line breaks

Variables & Types

  • No type declaration needed
  • Use snake_case for variable names
  • Basic types: int, float, str, bool

Operations

  • Arithmetic: +, -, *, /, //, %, **
  • Comparison: ==, !=, <, >, <=, >=
  • Logical: and, or, not

Best Practices

  • Use meaningful variable names
  • Add comments to explain complex logic
  • Convert input() results when needed
What's Next?

Great progress! You now understand Python's basic syntax and fundamental operations. In the next lessons, we'll explore:

  • Data structures: lists, tuples, dictionaries, and sets
  • Control flow: if/else statements and loops
  • Functions: creating reusable code blocks
  • Error handling: dealing with exceptions