0% found this document useful (0 votes)
1 views19 pages

Python Comprehensive Reference

This document is a comprehensive reference guide for the Python programming language, covering core syntax, built-in functions, data structures, object-oriented programming, and standard library modules. It provides examples of variable assignments, control flow structures, and various built-in functions, along with explanations of data structures like lists, dictionaries, and sets. Additionally, it highlights popular third-party modules for data science and best practices for advanced Python programming.

Uploaded by

mrtopper31
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views19 pages

Python Comprehensive Reference

This document is a comprehensive reference guide for the Python programming language, covering core syntax, built-in functions, data structures, object-oriented programming, and standard library modules. It provides examples of variable assignments, control flow structures, and various built-in functions, along with explanations of data structures like lists, dictionaries, and sets. Additionally, it highlights popular third-party modules for data science and best practices for advanced Python programming.

Uploaded by

mrtopper31
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming Language

Ultimate Comprehensive Reference: Commands, Functions, Built-ins &


Standard Modules

Author: Technical Reference Compilation


Scope: Syntax, Core Built-ins, Data Structures, OOP, Standard Library & Data Science Modules
Version: Complete Edition

Python Comprehensive Reference & Command Guide 1


1. Introduction & Core Syntax Fundamentals

Python is a high-level, interpreted, interactive, and object-oriented scripting language. Created by Guido van
Rossum and first released in 1991, Python's design philosophy emphasizes code readability with the notable use of
significant whitespace.

Variables and Assignment


Variables are created when you assign a value to it. Python has no command for declaring a variable beforehand.

# Variable declarations
name = "Python"
version = 3.12
is_awesome = True
x, y, z = 1, 2, 3

Basic Control Flow Structures


Conditional execution and iterative loops control the program flow.

# Conditional Branching
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"

# For and While Iteration


for i in range(3):
print(i)

count = 0
while count < 2:
count += 1

Python Comprehensive Reference & Command Guide 2


2. Built-in Functions Reference

Python provides a rich set of built-in functions that are always available without importing any external modules.

Python Comprehensive Reference & Command Guide 3


Function Description Example Usage

abs(x) Returns the absolute value of a number. abs(-5) → 5

Returns True if all elements of the iterable are


all(iterable) all([True, False]) → False
true.

Returns True if any element of the iterable is


any(iterable) any([False, True]) → True
true.

Returns a printable representation of an object


ascii(object) ascii('Café') → 'Café'
as a string.

Converts an integer to a binary string prefixed


bin(x) bin(10) → '0b1010'
with '0b'.

Converts a value to a boolean using standard


bool([x]) bool(1) → True
truth testing.

breakpoint() Drops into the debugger at the call site. breakpoint()

bytearray(...) Returns a mutable array of bytes. bytearray(5)

bytes([source[,
Returns a new immutable bytes object. bytes(4)
encoding]])

Returns True if the object appears callable,


callable(object) callable(print) → True
False otherwise.

Returns the string representing a Unicode


chr(i) chr(65) → 'A'
character code.

classmethod() Transforms a method into a class method. @classmethod

compile(...) Compiles source into code or AST object. compile('a=1', '', 'exec')

complex(real[, imag]) Creates a complex number. complex(2, 3) → (2+3j)

delattr(obj, name) Deletes an attribute from an object. delattr(x, 'attr')

dict(**kwarg) /
Creates a new dictionary. dict(a=1, b=2)
dict(mapping)

Without arguments, returns valid attributes;


dir([object]) dir(list)
with object, lists them.

Returns tuple of quotient and remainder of


divmod(a, b) divmod(9, 4) → (2, 1)
division.

Returns an enumerate object containing index


enumerate(iterable) list(enumerate(['a','b']))
and value pairs.

Python Comprehensive Reference & Command Guide 4


Function Description Example Usage

Evaluates a dynamically supplied python


eval(expression) eval('1 + 1') → 2
expression.

Python Comprehensive Reference & Command Guide 5


Python Comprehensive Reference & Command Guide 6
Built-in Functions (Continued)

Python Comprehensive Reference & Command Guide 7


Function Description Example Usage

exec(object) Dynamically executes Python code. exec('x = 5')

filter(function, Constructs an iterator from elements where filter(lambda x: x>0,


iterable) function returns true. [-1, 2])

float([x]) Converts a number or string to a float. float('3.14') → 3.14

format(value[,
Formats a value using a format specifier. format(0.5, '%') → '50.0%'
format_spec])

frozenset([iterable]) Returns a new immutable frozenset object. frozenset([1, 2])

Returns the value of a named attribute of an


getattr(object, name) getattr(str, 'upper')
object.

Returns a dictionary representing the current


globals() globals()
global symbol table.

Returns True if string matches an object attribute


hasattr(object, name) hasattr(x, 'shape')
name.

hash(object) Returns the hash value of an object if it has one. hash('test')

help([object]) Invokes the built-in help system. help(len)

Converts an integer to a lowercase hexadecimal


hex(x) hex(255) → '0xff'
string prefixed with '0x'.

Returns the "identity" of an object (unique


id(object) id(x)
integer memory address).

input([prompt]) Reads a string from standard input. name = input('Enter: ')

int([x]) Converts a number or string to an integer. int('10') → 10

isinstance(object,
Returns True if object is an instance of classinfo. isinstance(5, int) → True
classinfo)

issubclass(class, issubclass(bool, int) →


Returns True if class is a subclass of classinfo.
classinfo) True

iter(object) Returns an iterator object. iter([1, 2, 3])

Returns the length (number of items) of an


len(s) len([1, 2, 3]) → 3
object.

list([iterable]) Creates a list from an iterable. list((1, 2)) → [1, 2]

Updates and returns a dictionary of current local


locals() locals()
symbol table.

Python Comprehensive Reference & Command Guide 8


Python Comprehensive Reference & Command Guide 9
Built-in Functions (Part 3)

Python Comprehensive Reference & Command Guide 10


Function Description Example Usage

Applies function to every item of iterable and


map(function, iterable) map(abs, [-1, -2])
returns iterator.

max(iterable, *[, key, Returns the largest item in an iterable or


max([1, 5, 3]) → 5
default]) among two or more arguments.

Returns a memory view object created from


memoryview(obj) memoryview(b'abc')
the given arguments.

min(iterable, *[, key,


Returns the smallest item in an iterable. min([1, 5, 3]) → 1
default])

next(iterator[, default]) Retrieves the next item from the iterator. next(it)

Returns a featureless new object, base of all


object() obj = object()
classes.

Converts an integer to an octal string prefixed


oct(x) oct(8) → '0o10'
with '0o'.

Opens a file and returns a corresponding file f = open('[Link]',


open(file, mode='r')
object. 'r')

Given a string representing one Unicode


ord(c) ord('A') → 65
character, returns integer code.

Returns base to the power exp; if mod is


pow(base, exp[, mod]) pow(2, 3) → 8
present, returns base**exp % mod.

print(*objects, sep=' ', end=' print('Hello',


Prints objects to the text stream file.
') 'World')

property(get_x,
property(...) Returns a property attribute.
set_x)

Returns an immutable sequence of numbers


range([start], stop[, step]) range(0, 10, 2)
from start to stop.

Returns a string containing a printable


repr(object) repr('hello')
representation of an object.

reversed(seq) Returns a reverse iterator. reversed([1, 2, 3])

Rounds a number to a given precision in round(3.14159, 2) →


round(number[, ndigits])
decimal digits. 3.14

set([iterable]) Returns a new set object. set([1, 2, 2]) → {1, 2}

Sets the value of the named attribute given an


setattr(object, name, value) setattr(x, 'age', 25)
object.

Python Comprehensive Reference & Command Guide 11


Function Description Example Usage

slice(stop) / slice(start, Returns a slice object representing the set of


slice(1, 5, 2)
stop[, step]) indices specified.

sorted(iterable, *, key=None, Returns a new sorted list from the items in sorted([3, 1, 2]) → [1,
reverse=False) iterable. 2, 3]

Python Comprehensive Reference & Command Guide 12


3. Data Structures & Operations

Python's core built-in data structures—lists, tuples, dictionaries, and sets—offer powerful methods for data
manipulation.

Lists
Lists are ordered, mutable sequences allowing duplicate elements.

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


[Link]("orange") # Add element
[Link](1, "blueberry") # Insert at index
[Link]("banana") # Remove value
popped = [Link]() # Remove last element
[Link]() # Sort in place
sub_list = fruits[1:3] # Slicing

Dictionaries
Dictionaries store key-value pairs with fast O(1) average lookup times.

person = {"name": "Alice", "age": 30, "city": "New York"}


person["email"] = "alice@[Link]" # Add key
keys = [Link]() # Get keys
values = [Link]() # Get values
age = [Link]("age", 0) # Safe lookup

Sets and Tuples

# Tuples (immutable sequences)


coordinates = (10.0, 20.0)

# Sets (unordered collection of unique elements)


set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
union_set = set_a | set_b # {1, 2, 3, 4, 5, 6}
inter_set = set_a & set_b # {3, 4}

Python Comprehensive Reference & Command Guide 13


4. Object-Oriented Programming (OOP) in Python

Python is a multi-paradigm language offering full support for object-oriented programming through classes,
inheritance, encapsulation, and polymorphism.

Class Definition and Methods

class Animal:
# Class attribute
kingdom = "Animalia"

def __init__(self, name, species):


[Link] = name # Instance attribute
[Link] = species

def speak(self):
return f"{[Link]} makes a sound."

# Inheritance
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Canine")
[Link] = breed

def speak(self): # Method overriding


return f"{[Link]} barks!"

# Instantiation
dog = Dog("Buddy", "Golden Retriever")
print([Link]()) # Output: Buddy barks!

Special (Dunder) Methods


Dunder (double underscore) methods allow user-defined classes to emulate built-in behaviors.

Method Purpose / Trigger

__init__(self, ...) Constructor invoked upon object creation.

__str__(self) Informal string representation (used by print()).

__repr__(self) Official developer string representation.

__len__(self) Called by built-in len() function.

__eq__(self, other) Called for equality comparison (==).

Python Comprehensive Reference & Command Guide 14


5. Standard Library Modules Reference

Python's standard library comes with thousands of built-in modules to handle file input/output, operating system
tasks, mathematical calculations, and dates.

The math Module

import math

print([Link](16)) # 4.0
print([Link](5)) # 120
print([Link]) # 3.141592653589793
print([Link]([Link]/2))# 1.0

The os and sys Modules

import os
import sys

# Operating system interactions


print([Link]()) # Get current working directory
print([Link]('.')) # List files in directory

# System parameters
print([Link]) # Python interpreter version
print([Link]) # Command line arguments

The datetime Module

import datetime

now = [Link]()
print([Link]("%Y-%m-%d %H:%M:%S"))

future = now + [Link](days=7)


print([Link]())

Python Comprehensive Reference & Command Guide 15


The collections Module

from collections import Counter, defaultdict, namedtuple

# Counter for frequency counting


counts = Counter(['a', 'b', 'a', 'c', 'b', 'a'])
print(counts.most_common(1)) # [('a', 3)]

# Namedtuple for lightweight object creation


Point = namedtuple('Point', ['x', 'y'])
pt = Point(10, 20)

Python Comprehensive Reference & Command Guide 16


Standard Library Modules (Continued)

The json Module

import json

data = {"name": "Alice", "scores": [90, 85, 95]}


json_str = [Link](data) # Dict to JSON string
parsed = [Link](json_str) # JSON string to Dict

The itertools and functools Modules

import itertools
import functools

# Permutations and Combinations


perms = list([Link]([1, 2], 2))
# [(1, 2), (2, 1)]

# Reduce function
total = [Link](lambda x, y: x + y, [1, 2, 3, 4])
print(total) # 10

The re (Regular Expressions) Module

import re

text = "Contact support@[Link] for help."


match = [Link](r'[\w\.-]+@[\w\.-]+\.\w+', text)
if match:
print([Link]()) # support@[Link]

Python Comprehensive Reference & Command Guide 17


6. Popular Third-Party Ecosystem & Data Science Modules

Beyond the standard library, Python boasts a massive third-party package ecosystem managed via pip, powering
web development, machine learning, and data science.

NumPy (Numerical Python)


NumPy provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical
functions to operate on these arrays.

import numpy as np

arr = [Link]([1, 2, 3, 4, 5])


print(arr * 2) # Element-wise multiplication: [2, 4, 6, 8, 10]
print([Link]()) # 3.0
matrix = [Link]((3, 3)) # 3x3 zero matrix

Pandas (Data Analysis & Manipulation)


Pandas introduces DataFrames and Series for working with structured (tabular or sql-like) data efficiently.

import pandas as pd

df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 75000]
})

print([Link]()) # Summary statistics


print(df[df['Age'] > 28]) # Filtering rows

Requests (HTTP Client Library)


The requests module simplifies making HTTP web requests to APIs and servers.

import requests

response = [Link]('[Link]
if response.status_code == 200:
data = [Link]()
print([Link]('current_user_url'))

Python Comprehensive Reference & Command Guide 18


7. Advanced Python Commands & Best Practices

Advanced Python programming involves understanding generators, decorators, context managers, and exception
handling.

Exception Handling

try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Caught error: {e}")
finally:
print("Execution complete.")

Generators and Yield


Generators allow you to iterate over large data streams efficiently without loading everything into memory at once.

def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

for num in fibonacci(5):


print(num) # Outputs: 0, 1, 1, 2, 3

Context Managers (with statement)

# Automatically manages resource acquisition and cleanup


with open('[Link]', 'w') as f:
[Link]('Hello, Python World!')

Summary: Python's clean syntax, extensive built-in functions, and robust standard library modules make it the
world's most versatile language for scripting, automation, software engineering, and artificial intelligence.

Python Comprehensive Reference & Command Guide 19

You might also like