HomeTutorials

The Library

Python, defined.

Every keyword, function, type, and concept — with a one-line definition, its real-world use, and a tiny example.

01 · Definitions

print()

Built-in Function

Outputs text or values to the console.

Use · Display results, debug variables, show messages.

print("Hello, Pynexa!")

input()

Built-in Function

Reads a line of text typed by the user from the keyboard.

Use · Collect user data interactively.

name = input("Your name: ")
print("Hi", name)

len()

Built-in Function

Returns the number of items in a string, list, tuple, dict, etc.

Use · Measure size of any sequence.

len("python")  # 6

type()

Built-in Function

Returns the data type of an object.

Use · Inspect what kind of value you're holding.

type(42)  # <class 'int'>

range()

Built-in Function

Creates a sequence of integers from start to stop (exclusive).

Use · Drive for-loops, generate numeric series.

for i in range(1, 6):
    print(i)

int / float / str / bool

Data Type

The four primitive types: whole number, decimal, text, true/false.

Use · Represent all basic values in Python.

x = 5
y = 3.14
z = "hi"
f = True

list

Data Type

An ordered, mutable collection of items.

Use · Store sequences you may need to modify.

fruits = ["apple", "kiwi"]
fruits.append("mango")

tuple

Data Type

An ordered, immutable collection of items.

Use · Fixed groupings, dictionary keys, function returns.

point = (3, 4)
x, y = point

dict

Data Type

Key-value pairs with fast lookup.

Use · Map labels to values (records, configs, lookups).

user = {"name": "Sky", "age": 17}
print(user["name"])

set

Data Type

Unordered collection of unique items.

Use · Remove duplicates, fast membership tests.

s = {1, 2, 2, 3}  # {1, 2, 3}

if / elif / else

Control Flow

Runs different blocks of code based on conditions.

Use · Make decisions in your program.

n = 7
if n > 0:
    print("positive")
elif n == 0:
    print("zero")
else:
    print("negative")

for loop

Loop

Repeats a block once for each item in a sequence.

Use · Iterate over lists, strings, ranges, files.

for c in "PYNEXA":
    print(c)

while loop

Loop

Repeats a block as long as a condition is True.

Use · Loop until something changes — input, game state, etc.

n = 5
while n > 0:
    print(n)
    n -= 1

break

Loop Control

Exits the nearest enclosing loop immediately.

Use · Stop searching once you've found what you want.

for x in range(10):
    if x == 4: break
    print(x)

continue

Loop Control

Skips the rest of the current iteration and continues with the next.

Use · Ignore specific cases inside a loop.

for x in range(5):
    if x == 2: continue
    print(x)

pass

Statement

Does nothing — a placeholder where a statement is required.

Use · Stub functions, classes, or empty blocks.

def todo():
    pass

def (function)

Function

Defines a reusable block of code that may take inputs and return a value.

Use · Organize code, avoid repetition, build APIs.

def square(x):
    return x * x

print(square(5))

*args / **kwargs

Function

Accept any number of positional / keyword arguments.

Use · Flexible function signatures, wrappers, decorators.

def show(*args, **kw):
    print(args, kw)

lambda

Function

A small anonymous function written inline.

Use · Short one-off functions for sort/map/filter.

double = lambda x: x * 2
print(double(4))

return

Function

Sends a value back from a function to the caller.

Use · Produce outputs from functions.

def add(a, b):
    return a + b

class

OOP

A blueprint that bundles data (attributes) and behavior (methods).

Use · Model real-world objects, build reusable types.

class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        print(self.name, "woof!")

__init__

OOP

Special method that initializes a new object.

Use · Set up object state when it's created.

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

self

OOP

Reference to the current instance inside a method.

Use · Access instance attributes and other methods.

def name_of(self):
    return self.name

Inheritance

OOP

A class can derive attributes and methods from another class.

Use · Reuse and extend existing classes.

class Animal: pass
class Cat(Animal): pass

try / except

Error Handling

Run code that might fail and handle the error gracefully.

Use · Prevent crashes, recover from bad input or I/O.

try:
    x = int("abc")
except ValueError as e:
    print("bad:", e)

raise

Error Handling

Manually throw an exception.

Use · Signal invalid state or arguments.

if n < 0:
    raise ValueError("must be >= 0")

open()

File I/O

Opens a file for reading or writing.

Use · Read text/CSV/JSON, save data to disk.

with open("note.txt", "w") as f:
    f.write("hi")

with (context manager)

Statement

Automatically cleans up resources when a block exits.

Use · Files, locks, network connections.

with open("a.txt") as f:
    data = f.read()

import

Modules

Loads code from another module so you can use it.

Use · Reuse the standard library and 3rd-party packages.

import math
print(math.sqrt(16))

from ... import

Modules

Imports specific names from a module.

Use · Pull just what you need without prefixing.

from random import randint
print(randint(1, 10))

List comprehension

Expression

Compact syntax to build a list from an iterable with an optional filter.

Use · Replace many short for-loops with one line.

squares = [x*x for x in range(6)]

Dict comprehension

Expression

Compact syntax to build a dictionary.

Use · Transform pairs into a lookup table.

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

f-string

Syntax

Formatted string literal that embeds expressions inside { }.

Use · Readable string formatting.

name = "Sky"
print(f"Hello, {name}!")

Slicing

Syntax

Extract a portion of a sequence using [start:stop:step].

Use · Subsets of strings, lists, tuples.

nums = [0,1,2,3,4]
print(nums[1:4])  # [1,2,3]

math

Standard Library

Math functions: sqrt, sin, cos, log, pi, etc.

Use · Scientific or numeric computations.

import math
print(math.pi)

random

Standard Library

Generates pseudo-random numbers and choices.

Use · Games, sampling, shuffling.

import random
print(random.choice(["a","b","c"]))

datetime

Standard Library

Work with dates and times.

Use · Timestamps, age, scheduling.

from datetime import date
print(date.today())

json

Standard Library

Read and write JSON data.

Use · Configs, APIs, persistence.

import json
print(json.dumps({"a": 1}))

02 · Getting Started

From zero to your first running program — in six steps.

  1. 1

    1. Install Python

    Download the latest version from python.org. On Windows, tick 'Add Python to PATH' during install. On Mac/Linux, Python is often pre-installed — check with `python3 --version`.

  2. 2

    2. Pick an Editor

    VS Code (free, lightweight) or PyCharm (full IDE). Install the Python extension in VS Code for syntax help, autocomplete, and run-on-click.

  3. 3

    3. Your First File

    Create a file called hello.py and write: print("Hello, Pynexa!") Then run it from a terminal: python hello.py

  4. 4

    4. Use the REPL

    Type `python` (or `python3`) in a terminal to open an interactive shell. Try `2 + 2` or `print("hi")` — instant feedback.

  5. 5

    5. Install Packages

    Use pip — Python's package manager. Example: `pip install requests`. For projects, create a virtual environment: `python -m venv .venv` then activate it.

  6. 6

    6. Read Errors

    When something breaks, Python prints a traceback. Read it bottom-up: the last line tells you what went wrong; the lines above show where.

Recommended

Level-up resources

Ad slot · add VITE_ADSENSE_CLIENT to activate