15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
08.10.2024

Essential Python Commands Every Developer Should Master

Python is a high-level, interpreted programming language built around readability and expressive syntax. Its core built-in commands — covering I/O, type conversion, control flow, data structures, file handling, and module imports — allow developers to accomplish sophisticated tasks in remarkably few lines of code.

This reference covers the most critical Python commands in depth, including edge cases, common pitfalls, and production-relevant nuances that go beyond introductory tutorials. Whether you are automating server tasks on a VPS Hosting environment, building a Django API, or processing large datasets, these fundamentals underpin every Python workflow.

Input and Output Commands

The `print()` Function

`print()` writes output to `stdout` by default. Its full signature is:

“`python

print(*objects, sep=' ', end='n', file=sys.stdout, flush=False)

“`

Most developers only use the positional arguments, but the keyword parameters matter in production:

  • `sep` controls the separator between multiple objects (default: a single space).
  • `end` controls the terminating character (default: newline). Setting `end=''` is critical for progress indicators and inline output.
  • `file` redirects output to any writable stream — useful for writing structured logs directly to a file object.
  • `flush=True` forces the buffer to flush immediately, which is essential when monitoring long-running processes in real time.

“`python

Practical example: progress output without newlines

import time

for i in range(5):

print(f"Processing step {i+1}/5…", end='r', flush=True)

time.sleep(0.5)

print("Done. ")

“`

Pitfall: Using `print()` for logging in production code is an anti-pattern. Use the `logging` module instead — it provides log levels, timestamps, and configurable handlers without touching `stdout`.

The `input()` Function

`input()` reads a line from `stdin`, strips the trailing newline, and returns it as a `str`. The prompt argument is optional but should always be included for interactive scripts.

“`python

name = input("Enter your name: ")

print(f"Hello, {name}")

“`

Critical edge case: `input()` blocks execution indefinitely. In automated pipelines or scripts running on a server, an unexpected `input()` call will hang the process. Always guard interactive prompts with environment checks or use `argparse` / `sys.argv` for non-interactive input.

Type conversion is mandatory for numeric input:

“`python

try:

age = int(input("Enter your age: "))

except ValueError:

print("Invalid input: please enter a whole number.")

“`

Never cast `input()` output without a `try/except` block in any code that touches user-supplied data.

Variables, Data Types, and Type Introspection

`type()` and `isinstance()`

`type()` returns the exact class of an object. However, in most production code, `isinstance()` is the preferred tool because it respects inheritance hierarchies.

“`python

num = 42

print(type(num)) # <class 'int'>

print(isinstance(num, int)) # True

print(isinstance(num, (int, float))) # True — checks multiple types at once

“`

When to use each:

Use CaseRecommended Function
Exact type check (no subclasses)`type(x) is SomeClass`
Polymorphic / inheritance-aware check`isinstance(x, SomeClass)`
Debugging and introspection`type(x)`
Duck-typing validation`hasattr(x, 'method_name')`

Type Conversion: `int()`, `float()`, `str()`, `bool()`

These are constructor functions for Python's built-in types, not simple casting operators. They invoke the class `__init__` method and can accept a wide range of inputs.

“`python

int() with a base argument — often overlooked

binary_str = "1010"

print(int(binary_str, 2)) # Output: 10 (binary to decimal)

print(int("0xFF", 16)) # Output: 255 (hex to decimal)

bool() truthiness rules

print(bool(0)) # False

print(bool("")) # False

print(bool([])) # False

print(bool("False")) # True — non-empty string is always truthy

“`

Pitfall: `bool("False")` evaluates to `True` because it is a non-empty string. This catches many developers off guard when parsing configuration values.

`len()`

`len()` calls the object's `__len__` method and returns an integer. It works on strings, lists, tuples, dicts, sets, and any custom class implementing `__len__`.

“`python

text = "Python"

print(len(text)) # 6

data = {"a": 1, "b": 2}

print(len(data)) # 2 — counts keys, not key-value pairs

“`

Edge case: `len()` on a generator raises a `TypeError` because generators do not have a defined length. Use `sum(1 for _ in generator)` to count generator items, though this exhausts the generator.

Control Flow Commands

Conditional Statements: `if`, `elif`, `else`

Python evaluates conditions using truthiness, not strict boolean comparison. Understanding falsy values is essential:

  • Falsy: `None`, `0`, `0.0`, `""`, `[]`, `{}`, `set()`, `False`
  • Everything else is truthy

“`python

user_input = ""

if user_input:

print("Input received.")

else:

print("No input provided.") # This branch executes

“`

Ternary expression (inline conditional):

“`python

status = "adult" if age >= 18 else "minor"

“`

Structural pattern matching (Python 3.10+): For complex branching logic, `match/case` is more readable than long `elif` chains:

“`python

command = "start"

match command:

case "start":

print("Starting service…")

case "stop":

print("Stopping service…")

case _:

print("Unknown command.")

“`

Loops: `for` and `while`

`for` loops iterate over any iterable. The `range()` function generates integer sequences lazily, making it memory-efficient even for large ranges.

“`python

range(start, stop, step)

for i in range(0, 10, 2):

print(i) # 0, 2, 4, 6, 8

“`

`enumerate()` is the correct way to get both index and value — avoid using `range(len(iterable))`:

“`python

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits, start=1):

print(f"{index}. {fruit}")

“`

`while` loops require explicit termination logic. Always ensure the loop condition can become `False`, or include a `break` statement:

“`python

attempts = 0

max_attempts = 3

while attempts < max_attempts:

response = input("Enter password: ")

if response == "secret":

print("Access granted.")

break

attempts += 1

else:

The 'else' clause on a while loop executes if the condition

becomes False without hitting 'break' — a rarely used but powerful feature

print("Too many failed attempts.")

“`

Loop control keywords:

  • `break` — exits the loop immediately
  • `continue` — skips the rest of the current iteration
  • `pass` — a null statement, used as a placeholder in empty blocks

Built-in Data Structures

Python's four primary built-in data structures each have distinct performance characteristics and appropriate use cases.

Comparison of Python Data Structures

StructureOrderedMutableDuplicatesKey-ValueLookup Time
`list`YesYesYesNoO(n)
`tuple`YesNoYesNoO(n)
`dict`Yes (3.7+)YesKeys: NoYesO(1) avg
`set`NoYesNoNoO(1) avg
`frozenset`NoNoNoNoO(1) avg

Lists

Lists are dynamic arrays. Key operations and their time complexity:

“`python

fruits = ["apple", "banana", "cherry"]

fruits.append("orange") # O(1) amortized — adds to end

fruits.insert(1, "mango") # O(n) — shifts elements right

fruits.remove("banana") # O(n) — searches then removes

popped = fruits.pop() # O(1) — removes from end

popped_idx = fruits.pop(0) # O(n) — removes from beginning, avoid in hot loops

List comprehension — faster than equivalent for loop

squares = [x**2 for x in range(10)]

“`

Pitfall: Using `list.insert(0, item)` or `list.pop(0)` repeatedly is O(n) per operation. For queue behavior, use `collections.deque` which provides O(1) appends and pops from both ends.

Dictionaries

Since Python 3.7, dictionaries maintain insertion order as a language guarantee (not just an implementation detail).

“`python

person = {"name": "Alice", "age": 30, "role": "engineer"}

Safe key access — avoids KeyError

city = person.get("city", "Unknown") # Returns "Unknown" if key absent

Iterating

for key, value in person.items():

print(f"{key}: {value}")

Dictionary comprehension

squared = {x: x**2 for x in range(5)}

Merging dicts (Python 3.9+)

defaults = {"timeout": 30, "retries": 3}

config = {"timeout": 60}

merged = defaults | config # config values override defaults

“`

Sets

Sets use hash tables internally, giving O(1) average-case membership testing — far faster than lists for large collections.

“`python

unique_ids = {101, 202, 303, 101} # Duplicate 101 is silently dropped

print(unique_ids) # {101, 202, 303}

Set operations — extremely useful for data deduplication

a = {1, 2, 3, 4}

b = {3, 4, 5, 6}

print(a & b) # Intersection: {3, 4}

print(a | b) # Union: {1, 2, 3, 4, 5, 6}

print(a – b) # Difference: {1, 2}

print(a ^ b) # Symmetric difference: {1, 2, 5, 6}

“`

Functions: `def`, `return`, and `lambda`

Defining Functions with `def`

“`python

def calculate_discount(price, discount=0.10):

"""

Returns the discounted price.

Args:

price (float): Original price.

discount (float): Discount rate as a decimal. Default is 10%.

Returns:

float: Price after discount.

"""

return price * (1 – discount)

print(calculate_discount(100)) # 90.0

print(calculate_discount(100, 0.25)) # 75.0

“`

`*args` and `kwargs`** allow functions to accept variable numbers of arguments:

“`python

def log_event(event_type, *messages, **metadata):

print(f"[{event_type}]", " | ".join(messages))

for key, value in metadata.items():

print(f" {key}: {value}")

log_event("ERROR", "Connection failed", "Retrying…", host="db01", port=5432)

“`

Pitfall — mutable default arguments: Never use a mutable object (list, dict) as a default argument value. It is created once at function definition time, not on each call:

“`python

WRONG — the list persists between calls

def add_item(item, items=[]):

items.append(item)

return items

CORRECT

def add_item(item, items=None):

if items is None:

items = []

items.append(item)

return items

“`

Lambda Functions

Lambda expressions create anonymous single-expression functions. They are most useful as arguments to higher-order functions like `sorted()`, `map()`, and `filter()`.

“`python

Sorting a list of dicts by a specific key

users = [{"name": "Charlie", "age": 25}, {"name": "Alice", "age": 30}]

sorted_users = sorted(users, key=lambda u: u["age"])

filter() with lambda

even_numbers = list(filter(lambda x: x % 2 == 0, range(10)))

[0, 2, 4, 6, 8]

map() with lambda

doubled = list(map(lambda x: x * 2, [1, 2, 3]))

[2, 4, 6]

“`

When not to use lambda: If the function body is complex or needs a docstring, use `def`. PEP 8 explicitly discourages assigning a lambda to a variable name — that is what `def` is for.

File Handling

`open()`, `read()`, `write()`, and the `with` Statement

The `open()` function returns a file object. Its full signature includes a `mode` and `encoding` parameter:

“`python

Always specify encoding explicitly — avoids platform-dependent behavior

with open("data.txt", "r", encoding="utf-8") as f:

content = f.read()

“`

File modes:

ModeDescription
`"r"`Read (default). Raises `FileNotFoundError` if file absent.
`"w"`Write. Creates file or truncates existing content.
`"a"`Append. Creates file if absent, adds to end if present.
`"x"`Exclusive creation. Raises `FileExistsError` if file exists.
`"b"`Binary mode (combine with others: `"rb"`, `"wb"`).
`"+"`Read and write (combine with others: `"r+"`, `"w+"`).

Reading strategies:

“`python

Read entire file into memory — fine for small files

with open("config.txt", "r", encoding="utf-8") as f:

content = f.read()

Read line by line — memory-efficient for large files (logs, datasets)

with open("server.log", "r", encoding="utf-8") as f:

for line in f:

process(line.strip())

Read all lines into a list

with open("hosts.txt", "r", encoding="utf-8") as f:

lines = f.readlines()

“`

Why `with` is mandatory in production: The `with` statement uses the context manager protocol (`__enter__` / `__exit__`) to guarantee the file is closed even if an exception is raised inside the block. Manually calling `f.close()` is error-prone — if an exception occurs before `close()`, the file descriptor leaks.

Pitfall: Opening a file in `"w"` mode immediately truncates it to zero bytes, even before you write anything. If your write logic fails, the original content is already gone. Use `"x"` mode or write to a temporary file and rename atomically:

“`python

import os

import tempfile

with tempfile.NamedTemporaryFile("w", delete=False, encoding="utf-8") as tmp:

tmp.write(new_content)

tmp_path = tmp.name

os.replace(tmp_path, "config.txt") # Atomic on POSIX systems

“`

Importing Modules

`import`, `from … import`, and `as`

Python's module system is one of its greatest strengths. The standard library covers cryptography, networking, concurrency, data serialization, and much more.

“`python

import math

print(math.sqrt(144)) # 12.0

print(math.ceil(4.2)) # 5

print(math.floor(4.9)) # 4

Import specific names into the current namespace

from os.path import join, exists, dirname

Alias long module names

import numpy as np

import pandas as pd

“`

Useful standard library modules for server-side Python:

ModulePurpose
`os` / `pathlib`File system operations, path manipulation
`sys`Interpreter state, `argv`, `stdin`/`stdout`/`stderr`
`subprocess`Spawn and communicate with system processes
`logging`Production-grade logging with levels and handlers
`json`Serialize/deserialize JSON data
`re`Regular expressions
`datetime`Date and time arithmetic
`collections``deque`, `Counter`, `defaultdict`, `OrderedDict`
`itertools`Memory-efficient iteration combinators
`functools``lru_cache`, `partial`, `reduce`
`threading` / `multiprocessing`Concurrency and parallelism
`socket`Low-level networking
`hashlib`Cryptographic hashing (SHA-256, MD5, etc.)

Managing Third-Party Packages

Beyond the standard library, the Python Package Index (PyPI) hosts over 500,000 packages. Use `pip` to install them and always work inside a virtual environment:

“`bash

Create and activate a virtual environment

python3 -m venv .venv

source .venv/bin/activate # Linux/macOS

.venvScriptsactivate.bat # Windows

Install packages

pip install requests flask gunicorn

Freeze dependencies for reproducible deployments

pip freeze > requirements.txt

Recreate environment on another machine

pip install -r requirements.txt

“`

Pitfall: Installing packages globally (without a virtual environment) pollutes the system Python and causes dependency conflicts between projects. On a production VPS Hosting server, always use per-project virtual environments or containerization.

Deploying Python Applications on a Server

Understanding Python commands is only half the picture. Running Python code reliably in a server environment requires additional considerations.

When you deploy a Flask or Django application on a VPS with cPanel or a bare Linux VPS, the standard workflow involves:

  1. A WSGI server (Gunicorn, uWSGI) to serve the Python application
  2. A reverse proxy (Nginx, Apache) to handle SSL termination and static files
  3. A process manager (systemd, Supervisor) to keep the application running after crashes and reboots
  4. Environment variable management for secrets (never hardcode credentials)

“`bash

Example: running a Flask app with Gunicorn

gunicorn –workers 4 –bind 0.0.0.0:8000 wsgi:app

Example: systemd service unit for auto-restart

/etc/systemd/system/myapp.service

[Unit]

Description=My Python App

After=network.target

[Service]

User=deploy

WorkingDirectory=/var/www/myapp

ExecStart=/var/www/myapp/.venv/bin/gunicorn –workers 4 –bind 0.0.0.0:8000 wsgi:app

Restart=always

[Install]

WantedBy=multi-user.target

“`

For resource-intensive workloads such as machine learning inference or large-scale data processing, GPU Hosting provides CUDA-capable hardware that dramatically accelerates NumPy, TensorFlow, and PyTorch operations.

If your Python application sends transactional emails or manages mailing lists, pairing it with a dedicated Email Hosting service ensures reliable delivery and proper SPF/DKIM configuration rather than relying on a local `sendmail` setup.

Key Takeaway Checklist

Use this as a pre-deployment and code-review reference:

  • I/O: Replace `print()` with the `logging` module in any code that runs unattended. Always wrap `input()` in `try/except ValueError`.
  • Type checking: Prefer `isinstance()` over `type()` for validation logic. Remember that `bool("False")` is `True`.
  • Data structures: Use `dict` or `set` for O(1) lookups. Use `collections.deque` instead of `list` when you need a queue.
  • Functions: Never use mutable objects as default argument values. Document all public functions with docstrings.
  • File handling: Always use `with open(…)` and always specify `encoding="utf-8"` explicitly. Use atomic writes for critical files.
  • Modules: Always work inside a virtual environment. Pin dependencies with `pip freeze > requirements.txt`.
  • Control flow: Exploit the `else` clause on `for`/`while` loops for post-loop logic. Use `match/case` (Python 3.10+) for complex branching.
  • Deployment: Use a WSGI server, a process manager, and environment variables for secrets. Never run a Flask development server in production.

Frequently Asked Questions

What is the difference between `print()` and `logging` in Python?

`print()` writes directly to `stdout` with no metadata. The `logging` module provides severity levels (`DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`), timestamps, module names, and configurable output destinations. For any script running in production or as a background service, `logging` is the correct tool.

Why does Python's `input()` always return a string?

`input()` reads raw bytes from `stdin` and decodes them as text. Python cannot know whether the user intends to provide a number, a date, or a string, so it returns the most general type (`str`) and delegates type conversion to the developer. This design forces explicit validation, which is safer than implicit coercion.

What is the performance difference between a `list` and a `set` for membership testing?

Checking `x in my_list` is O(n) — Python scans every element. Checking `x in my_set` is O(1) on average because sets use a hash table. For collections with more than a few dozen elements where you frequently test membership, converting to a `set` provides a dramatic speed improvement.

When should I use a `lambda` instead of a `def` function?

Use `lambda` only when passing a short, single-expression function as an argument to another function (e.g., `sorted()`, `map()`, `filter()`). If the logic requires more than one expression, needs error handling, or will be reused elsewhere, define it with `def`. Assigning a `lambda` to a variable name is explicitly discouraged by PEP 8.

How do I run a Python script automatically on a Linux server after a reboot?

The most robust method is a `systemd` service unit with `Restart=always` and `WantedBy=multi-user.target`. Alternatively, add the script to the `crontab` with `@reboot /path/to/venv/bin/python /path/to/script.py`. The `systemd` approach is preferred because it provides logging via `journalctl`, dependency ordering, and fine-grained restart policies.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started