Core Concepts of Python Programming

Execution Models and Language Characteristics

Computers only understand machine language. High-level code must be translated using either compilation or interpretation.

  • Compiled languages: Source code is converted to machine code before execution. This yields faster runtime performance but reduced portability.
  • Interpreted languages: Code is executed line-by-line at runtime. Slower execution, but better cross-platform compatibility.

Python is an interpreted, dynamically typed, object-oriented language where everything—including functions, modules, and primitive types—is an object. It features a rich standard library and extensive third-party ecosystem for domains like data science, web development, and automation.

Variables and Data Types

Variables store data and are created upon assignment:

name = "Alice"
age = 30

Python supports:

  • Numeric types: int, float, bool (True/False), complex
  • Non-numeric types: str, list, tuple, dict

All non-numeric types support sequence operations: indexing ([]), iteration (for), slicing, concatanation (+), and repetition (*).

Type Behavior

  • Numeric types can be used in arithmetic expressions. bool values act as 1 (True) or 0 (False).
  • Strings concatenate with + and repeat with * (e.g., "Hi" * 3"HiHiHi").
  • Mixing strings and numbers in arithmetic raises a TypeError.

Input and Output

Use input() to read user input (always returns a string):

user_input = input("Enter your name: ")

Format output using the % operater:

print("Name: %s, Age: %d" % (name, age))

Naming and Scope

Identifiers (variable/function names) must:

  • Start with a letter or underscore
  • Contain only letters, digits, or underscores
  • Not match Python keywords
  • Be case-sensitive

Use snake_case for variables and functions; PascalCase for classes.

Variable References and Mutability

In Python, variables hold references to objects in memory. Use id() to inspect memory addresses.

  • Immutable types: int, float, str, tuple — cannot be changed in place.
  • Mutable types: list, dict — can be modified via methods.

Dictionary keys must be immutable to allow hashing.

Local vs Global Scope

  • Local variables: Defined inside functions; destroyed when the function exits.
  • Global variables: Defined outside functions; accessible everywhere.

To modify a global variable inside a function, declare it with global:

counter = 0

def increment():
    global counter
    counter += 1

Operators

Arithmetic

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division (float)
// Floor division
% Modulo
** Exponentiation

Precedence: ** > * / // % > + -

Comparison and Logic

Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not

Assignment shortcuts: +=, -=, *=, etc.

Strings

Defined with single or double quotes. Support:

  • Indexing: s[0], s[-1]
  • Slicing: s[start:end:step] (end-exclusive)
  • Methods:
    • Case: .upper(), .lower(), .title()
    • Search: .find(), .startswith(), .replace()
    • Whitespace: .strip(), .lstrip(), .rstrip()
    • Split/Join: .split(), .join()

Lists

Ordered, mutable sequences defined with []:

items = ["apple", "banana"]

Common operations:

  • Append: .append(x)
  • Insert: .insert(i, x)
  • Remove: .remove(x), .pop(i), del items[i]
  • Sort: .sort(), .reverse()
  • Length: len(items)

Iterate with for:

for item in items:
    print(item)

Tuples

Immutable sequences defined with ():

point = (10, 20)
single = (42,)  # comma required for single-element tuples

Used for fixed data, function return values, and dictionary keys. Convert to/from lists using list() and tuple().

Dictionaries

Unordered key-value mappings defined with {}:

person = {"name": "Bob", "age": 25}

Keys must be immutable. Access values via keys:

for key in person:
    print(f"{key}: {person[key]}")

Control Flow

Conditionals

if temperature > 30:
    print("Hot")
elif temperature > 20:
    print("Warm")
else:
    print("Cool")

Loops

while loop:

count = 0
while count < 5:
    print(count)
    count += 1

for loop (with optional else):

for i in range(3):
    if found:
        break
else:
    print("Not found")

Use break to exit early; continue to skip to the next iteration.

Functions

Define with def:

def greet(name):
    return f"Hello, {name}!"
  • Parameters: Inputs during definition (formal parameters)
  • Arguments: Values passed during call (actual arguments)

Advanced Parameters

  • Default values: def func(x=10): ...
  • Variable args: *args (tuple), **kwargs (dict)
def process(*items, **options):
    pass

process("a", "b", debug=True)

Call with unpacking:

values = [1, 2]
opts = {"flag": True}
process(*values, **opts)

Recursion

A function calling itself, requiring a base case to terminate:

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

Utilities

  • print() customization: Use end="" to suppresss newline.
  • Comments: # for single-line; triple quotes for multi-line.
  • Built-in functions: len(), max(), min(), del
  • Membership tests: in, not in (checks keys in dicts)

Escape sequences: \n (newline), \t (tab), \\ (backslash).

Tags: python programming Variables Data Types Control Flow

Posted on Tue, 18 Aug 2026 16:54:02 +0000 by marco839