WisdomEye Logo
WisdomEye

Python for Beginners with Hands-On Projects

Summary

This comprehensive Python course for beginners covers fundamental programming concepts and practical applications. It starts with installing Python and a beginner-friendly code editor (Zed), then delves into core Python elements like data types, variables, operators, conditional statements (if, elif, else), loops (for, while), and functions. The course emphasizes hands-on learning with projects such as a password generator, MAC address generator, calculator, port scanner, and password cracker. It also introduces essential modules like OS, Math, Random, Datetime, and Socket for system interaction, calculations, generating random data, handling dates/times, and basic networking, concluding with file handling, error handling, and creating custom modules.

Key Insights

Python is a high-level, general-purpose programming language versatile across many fields like web development, data science, and cybersecurity.

Python is a high-level, general-purpose programming language, meaning it's not restricted to a single task and can be used for web development, automation, data science, machine learning, cybersecurity, scripting, and more. This versatility makes it the most popular language learned by IT professionals regardless of their specialization.

Python's generality and readability make it a mandatory skill for IT professionals.

Python's versatility and ease of use make it a mandatory skill for IT professionals, playing a role in their day-to-day work, regardless of specialization.

Choose Zed code editor over VS Code for its lightweight performance, ideal for beginners and low-end systems.

Zed code editor is chosen over VS Code for being lightweight, fast, and efficient, consuming minimal system resources. It offers essential features like syntax highlighting and autocompletion, making it ideal for beginners and low-end systems, unlike heavier editors like VS Code.

A variable acts as a container to store data, enabling data storage and reusability in programs.

A variable is a container that stores data (numbers, text, etc.). It solves data storage and reusability problems, eliminating the need to repeatedly type lengthy or complex data.

Primary data types include integers (int), floating-point numbers (float), and strings (str).

Primary data types store different forms of data: integers (int) for whole numbers, floats (float) for decimal numbers, and strings (str) for text. Python automatically determines the data type.

Use f-strings (formatted string literals) for efficient variable and expression insertion into strings.

f-strings, enabled by prefixing a string with 'f', allow embedding variables and expressions directly within curly braces '{}' inside the string for clean and readable formatting.

Boolean values are 'True' or 'False', representing one or zero respectively in numerical contexts.

Boolean values are 'True' (represented as 1) or 'False' (represented as 0). They are the result of logical operations and are crucial for decision-making in programs.

Data types returned by 'input()' are always strings; use type casting (e.g., int(), float()) to convert them for calculations.

User input via 'input()' is always treated as a string. Use type casting functions like 'int()' or 'float()' to convert input into numbers for mathematical operations, preventing 'type errors'.

Use 'elif' (else if) to check multiple sequential conditions after an initial 'if' statement.

'elif' allows checking multiple conditions sequentially. If the 'if' condition is false, the first 'elif' is checked. If that's false, the next 'elif' is checked, and so on. The first condition to evaluate as true determines which block gets executed.

Loops automate repetitive tasks, executing code blocks multiple times to avoid redundant code.

Loops automate repetitive tasks by executing a block of code multiple times, saving time and effort compared to writing the same code repeatedly.

Functions create modular, reusable code blocks, simplifying program structure and maintenance.

Functions break programs into smaller, reusable units (modules). This improves code organization, making it easier to develop, maintain, debug, and update large applications.

Lists are ordered, mutable collections storing various data types, accessed by index.

Lists are ordered, mutable collections storing items of potentially different data types. Items are accessed using numerical indices starting from 0. They can be modified (add, remove, change elements) after creation.

Tuples are ordered, immutable collections, defined with parentheses and accessed by index.

Tuples are similar to lists but are immutable, meaning their contents cannot be changed after creation. They are defined using parentheses '()' and are indexed starting from 0.

Dictionaries store data as key-value pairs, offering fast lookups via keys.

Dictionaries store data in key-value pairs (e.g., {'name': 'Alice'}). Keys must be unique and immutable (like strings or numbers), while values can be of any data type. They allow fast data retrieval using keys.

Sets store unique, unordered items and automatically discard duplicates.

Sets are unordered collections of unique items. They automatically remove duplicate elements upon creation or addition. Sets are mutable (elements can be added/removed) but do not support indexing.

Runtime errors (exceptions) crash programs; use try/except blocks to handle them gracefully.

Runtime errors (exceptions) halt program execution. The 'try' block contains code that might raise an error, and the 'except' block handles the error if it occurs, preventing the program from crashing.

The 'socket' module enables network communication, allowing programs to send and receive data over the internet.

The 'socket' module provides tools for network programming, enabling systems to communicate. It supports protocols like TCP and UDP for exchanging data and interacting with network services.

Sections

Introduction and Setup

Learn Python programming from scratch with a step-by-step, project-based course designed for absolute beginners and those with no prior coding experience.

This course is designed for absolute beginners or anyone with zero coding experience who has struggled to learn Python or programming in general. It teaches concepts step-by-step from level zero in a logical and sequential order. The course is project-based, focusing on building hands-on, real-world projects to apply learned concepts.

Meet the instructor, San Malu, a cybersecurity analyst and malware reverse engineer.

The instructor, San Malu, is a cybersecurity analyst and malware reverse engineer. He emphasizes that true learning in programming happens through building real-world applications by integrating different concepts and logic.

Projects include a password generator, MAC address generator, calculator, port scanner, and password cracker.

The course features several hands-on projects to apply learning, including a password generator, MAC address generator, calculator, port scanner, and password cracker, among others.

Python is a high-level, general-purpose programming language versatile across many fields like web development, data science, and cybersecurity.

Python is a high-level, general-purpose programming language, meaning it's not restricted to a single task and can be used for web development, automation, data science, machine learning, cybersecurity, scripting, and more. This versatility makes it the most popular language learned by IT professionals regardless of their specialization.

High-level languages like Python are human-readable and easier to learn than low-level languages.

Python is a high-level language, designed to be human-readable, making it easier to learn and write. It uses words and structures similar to natural language, unlike low-level languages like C or assembly, which interact more directly with hardware and have complex syntax.

Python's generality and readability make it a mandatory skill for IT professionals.

Python's versatility and ease of use make it a mandatory skill for IT professionals, playing a role in their day-to-day work, regardless of specialization.

Install the Python interpreter, a program that reads and executes Python code by translating it into machine-level instructions.

Before running Python code, the Python interpreter must be installed. This program reads and executes Python code, translating high-level language instructions into machine-level commands that the computer can understand.

Download and install Python from python.org, ensuring to add Python.exe to the system's PATH.

Download Python from python.org. For Windows installation, double-click the installer and critically check the 'Add Python.exe to PATH' option to make Python accessible from the terminal. For macOS, download the .pkg installer.

Verify Python installation by opening PowerShell and typing 'py' to enter the Python console.

After installation, open PowerShell, type 'py', and press Enter to verify. If successful, you'll enter the Python console, indicating a successful installation. Type 'python --version' to check the installed version.

Choose Zed code editor over VS Code for its lightweight performance, ideal for beginners and low-end systems.

Zed code editor is chosen over VS Code for being lightweight, fast, and efficient, consuming minimal system resources. It offers essential features like syntax highlighting and autocompletion, making it ideal for beginners and low-end systems, unlike heavier editors like VS Code.

Download and install Zed code editor from zed.dev for Windows and macOS (including Apple Silicon).

Download Zed code editor from zed.dev. Installers are available for Windows and macOS, supporting both Intel-based and Apple Silicon chips (M1, M2, M3, etc.).

Configure Zed editor: adjust font size, select a theme (e.g., dark theme), and install extensions like 'One Dark Pro'.

Configure Zed by setting font size (e.g., 18), selecting themes (like the default dark theme or others like 'One Dark Pro' via extensions), and exploring the extension marketplace for additional functionality.


Your First Python Program

Create a new Python file (e.g., 'hello.py') and save it with the '.py' extension.

Open Zed editor, go to File > New to create a new file. Write a simple 'print('hello world')' statement. Save the file with a '.py' extension (e.g., 'hello.py') in a dedicated folder for Python files.

Execute Python files using 'py <filename.py>' in the integrated terminal.

Open the integrated terminal in Zed (bottom right). Type 'py <filename.py>' (or 'python3 <filename.py>' on Mac) to execute the Python script. The output will appear directly in the terminal.

The 'print()' function displays output to the terminal, essential for user feedback and displaying results.

The 'print()' function displays or outputs information to the terminal. It's used for displaying messages, calculation results, or any data needed by the user when a program runs.

A string is the technical term for text in programming, always enclosed in quotes (single or double).

A string is the technical name for text in programming. It is always enclosed within single (' ') or double (' ') quotes. Anything within quotes, including numbers or symbols, is treated as a string.

A statement is an instruction given to the program, like telling Python to print something or perform a calculation.

A statement is an instruction given to the program. Python executes these instructions sequentially. Examples include printing output or performing mathematical calculations.

Use triple quotes (''' or """) to define multi-line strings, overcoming Python's single-line string limitation.

To write strings spanning multiple lines, use triple single quotes (''') or triple double quotes (""") at the beginning and end. Python interprets text within triple quotes as a single multi-line string.

Escape sequences, like '\n' for new lines and '\t' for tabs, customize string output within a single line.

Escape sequences, starting with a backslash (\), represent characters difficult to type directly. '\n' creates a new line, and '\t' creates a tab (four spaces). They allow formatting within a single string.

Comments (starting with '#') are ignored by Python during execution, used for explaining code to improve readability and maintainability.

Comments start with a hash symbol ('#') and are ignored by Python during execution. They are used to explain code logic, improving readability and maintainability for developers, especially in team environments or for future reference.

Disable code temporarily by prefixing lines with '#', allowing easy reactivation later.

Code lines can be temporarily disabled by adding a '#' at the beginning. This is useful for testing or debugging, as Python ignores commented-out lines during execution.


Variables and Data Types

A variable acts as a container to store data, enabling data storage and reusability in programs.

A variable is a container that stores data (numbers, text, etc.). It solves data storage and reusability problems, eliminating the need to repeatedly type lengthy or complex data.

Use variables to store data like account numbers, avoiding manual repetition and reducing errors.

Storing lengthy data like bank account numbers in variables (e.g., ACC = '...') makes programs easier to manage, reduces typing errors, and simplifies data access.

The assignment operator ('=') stores data into a variable, creating the variable upon assignment.

The equal sign ('=') is the assignment operator; it assigns data to a variable. A variable is created in Python as soon as data is assigned to it.

Never enclose variable names in quotes when accessing them; this treats them as strings instead of variables.

When accessing variables, do not enclose them in quotes (' ' or " "). Doing so makes Python treat them as strings, not variables, preventing access to the stored data.

When assigning string values, always use single or double quotes; numbers should not be quoted to be treated as numerical types.

Surround string values with quotes (' ' or " "). Do not quote numbers, as Python will treat quoted numbers as strings, preventing numerical operations.

Variables can be reused multiple times throughout a program simply by referencing their name.

Variables are reusable; once created, their value can be accessed multiple times by using their name, eliminating redundant code.

Variable names cannot start with a number but can contain numbers, underscores, and letters, respecting case sensitivity.

Variable names cannot start with a number but can contain numbers (not at the beginning), underscores ('_'), and letters. Python is case-sensitive (e.g., 'myVar' and 'myvar' are different). Underscores are the only special character allowed.

Primary data types include integers (int), floating-point numbers (float), and strings (str).

Primary data types store different forms of data: integers (int) for whole numbers, floats (float) for decimal numbers, and strings (str) for text. Python automatically determines the data type.

Use the 'type()' function to determine the data type of a variable.

The 'type(variable)' function returns the data type of the value stored in a variable (e.g., int, float, str, bool).

Python automatically infers data types, eliminating the need for explicit type declarations.

Python automatically detects the data type of a value assigned to a variable, eliminating the need for explicit type declarations like in some other languages.


String Methods

String methods allow efficient manipulation and analysis of text data.

Python's built-in string methods enable efficient manipulation and analysis of strings. They are essential for text processing tasks like finding length, changing case, slicing, and modifying strings.

Use 'len(string)' to count the number of characters in a string, including spaces.

The 'len(string)' function counts the total number of characters in a string, including spaces. It can take a string literal or a string variable as input.

Convert strings to uppercase using '.upper()' and to lowercase using '.lower()'.

Use the '.upper()' method to convert all characters in a string to uppercase and '.lower()' to convert them to lowercase. These methods return new strings; they don't modify the original.

'.capitalize()' converts the first letter of a string to uppercase, while '.title()' capitalizes the first letter of each word.

'.capitalize()' converts only the first character of a string to uppercase. '.title()' capitalizes the first character of every word within a string.

Use '.replace('old', 'new')' to substitute occurrences of a substring within a string.

The '.replace('old', 'new')' method finds all occurrences of the 'old' substring and replaces them with the 'new' substring. It returns a new string with the replacements made.

String slicing extracts specific portions of a string using index ranges [start:end].

String slicing extracts a portion of a string using index notation. '[start:end]' extracts characters from the 'start' index up to (but not including) the 'end' index. Negative indices count from the end.

'.count('substring')' returns the number of non-overlapping occurrences of a substring within a string.

The '.count('substring')' method counts how many times a specific substring appears within a larger string. It returns the count as an integer.

'.strip()', '.rstrip()', and '.lstrip()' remove whitespace from the beginning, end, or both ends of a string.

'.strip()' removes leading and trailing whitespace (spaces, tabs, newlines). '.rstrip()' removes only trailing whitespace, and '.lstrip()' removes only leading whitespace.


String Formatting

Use f-strings (formatted string literals) for efficient variable and expression insertion into strings.

f-strings, enabled by prefixing a string with 'f', allow embedding variables and expressions directly within curly braces '{}' inside the string for clean and readable formatting.

Control decimal places in f-strings using the format specifier ':.nf', where 'n' is the number of decimal places.

To control decimal places in f-strings, use the format specifier ':.nf' after a variable or expression within curly braces, where 'n' specifies the number of decimal places to display.

The '.format()' method inserts variables or expressions into placeholder curly braces '{}' within a string.

The '.format()' method acts as a string formatter. Placeholders '{}' are used within the string, and the '.format(variable1, variable2, ...)' method inserts the provided variables into these placeholders in order.


Operators and Operations

Operators are symbols performing mathematical or logical operations on values or variables.

Operators are symbols used to perform specific mathematical or logical operations on data values or variables. They take input values and produce an output based on the defined operation.

Arithmetic operators include +, -, *, /, and % (modulus) for calculations.

Arithmetic operators perform basic mathematical calculations: addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) which returns the remainder of a division.

Store calculation results in variables for reusability and cleaner code.

Storing the results of calculations in variables is a convenient and preferred way to manage results, allowing them to be reused later in the program without recalculation.

Format numerical output with many decimal places using f-strings and ':.nf' specifier.

To control decimal places in division results (or other floats), use f-strings with the ':.nf' format specifier (e.g., ':.2f' for two decimal places).

Boolean values are 'True' or 'False', representing one or zero respectively in numerical contexts.

Boolean values are 'True' (represented as 1) or 'False' (represented as 0). They are the result of logical operations and are crucial for decision-making in programs.

Relational operators (e.g., >, <, ==) compare two values, returning True or False.

Relational (or comparison) operators compare two values and return a boolean result (True or False). Examples include greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=).

Logical operators (and, or, not) combine multiple conditions for complex decision-making.

Logical operators combine multiple conditions. 'and' requires all conditions to be true. 'or' requires at least one condition to be true. 'not' inverts the boolean value of a condition.

Equality operators (==, !=) check if two values are identical or different, returning True or False.

Equality operators check for value equality. '==' returns True if values are equal, '!=' returns True if values are not equal. Double equals (==) are used for comparison, single equals (=) for assignment.

Use the 'input()' function to collect user input, specifying a prompt message.

The 'input()' function prompts the user for data entry with a specified message (prompt) and returns the input as a string. This makes programs interactive.

Data types returned by 'input()' are always strings; use type casting (e.g., int(), float()) to convert them for calculations.

User input via 'input()' is always treated as a string. Use type casting functions like 'int()' or 'float()' to convert input into numbers for mathematical operations, preventing 'type errors'.

Type casting (e.g., int(), float()) converts data from one type to another, essential for processing user input.

Type casting converts data from one type to another. 'int()' converts to integer, 'float()' to decimal, 'str()' to string. This is crucial for using user input correctly in operations.

The '+' operator concatenates strings but performs addition on numbers.

The '+' operator behaves differently based on data type: it concatenates strings (joins them) but performs mathematical addition on numbers.


Control Flow: Conditional Statements

If statements execute code blocks based on whether a condition is true or false.

An 'if' statement checks a condition. If the condition is true, the indented code block following 'if' is executed. Otherwise, it's skipped.

Indentation (spaces) defines code blocks belonging to 'if', 'else', 'elif', loops, and functions.

Indentation (typically four spaces) defines code blocks. All lines within a block must have the same indentation level, indicating they belong to the preceding control structure (if, for, while, function).

The 'else' statement provides an alternative code block to execute when the 'if' condition is false.

An 'else' statement follows an 'if' statement. Its indented block executes only if the preceding 'if' condition evaluates to false.

Use 'elif' (else if) to check multiple sequential conditions after an initial 'if' statement.

'elif' allows checking multiple conditions sequentially. If the 'if' condition is false, the first 'elif' is checked. If that's false, the next 'elif' is checked, and so on. The first condition to evaluate as true determines which block gets executed.

The 'else' block in an 'elif' chain executes only if all preceding 'if' and 'elif' conditions are false.

The final 'else' block in an 'if-elif-else' structure executes only if none of the preceding 'if' or 'elif' conditions evaluate to true.

Equality operators ('==' for equal, '!=' for not equal) compare values and return a boolean result.

Equality operators compare values. '==' checks if two values are equal (returning True or False). '!=' checks if values are not equal (returning True or False).

The 'not' logical operator inverts a boolean condition (True becomes False, False becomes True).

The 'not' operator negates a boolean value. If a condition is True, 'not condition' becomes False. If a condition is False, 'not condition' becomes True.


Loops

Loops automate repetitive tasks, executing code blocks multiple times to avoid redundant code.

Loops automate repetitive tasks by executing a block of code multiple times, saving time and effort compared to writing the same code repeatedly.

The 'for' loop iterates over a sequence (like a list or range) executing a block for each item.

A 'for' loop iterates through items in a sequence (list, string, range, etc.). For each item, it assigns the item to a variable and executes the indented code block.

'range(start, stop, increment)' generates a sequence of numbers for loops.

The 'range(start, stop, increment)' function generates a sequence of numbers. 'stop' is exclusive (runs up to stop-1). If 'increment' is omitted, it defaults to 1. If 'start' is omitted, it defaults to 0.

The 'in' keyword connects a loop variable to a sequence, assigning each item sequentially.

The 'in' keyword links the loop variable (e.g., 'i') to the sequence (e.g., 'range' or a list), assigning each item from the sequence to the variable for each iteration.

Use 'break' to exit a loop prematurely when a specific condition is met.

The 'break' statement immediately terminates the current loop, regardless of the loop's condition. Execution continues after the loop block.

Use 'continue' to skip the current iteration of a loop and proceed to the next.

The 'continue' statement skips the rest of the current loop iteration. Execution jumps directly to the next iteration of the loop, without executing code after 'continue' within that iteration.

The 'while' loop repeats a block of code as long as a specified condition remains true.

A 'while' loop executes its indented block of code repeatedly as long as the condition specified in the 'while' statement evaluates to True. It requires manual initialization and updating of loop control variables.

While loops require manual initialization, condition checking, and increment/decrement of control variables.

Unlike 'for loops' where iteration details are often handled by the sequence, 'while loops' require explicit initialization of a counter/variable before the loop, condition checking within the 'while' statement, and manual incrementing/decrementing of the variable inside the loop body.


Functions

Functions create modular, reusable code blocks, simplifying program structure and maintenance.

Functions break programs into smaller, reusable units (modules). This improves code organization, making it easier to develop, maintain, debug, and update large applications.

Define functions using 'def function_name():', followed by an indented code block.

Use the 'def' keyword, followed by the function name, parentheses '()', and a colon ':' to define a function. The code belonging to the function is indented below.

Call a function by writing its name followed by parentheses: 'function_name()'.

To execute a function's code, you must 'call' it by writing its name followed by parentheses '()'. Functions execute only when called.

Functions must be called *after* their definition.

A function must be defined before it can be called. Calling a function before its definition will result in an error.

Pass arguments (data) into functions via parameters defined in the function signature.

Arguments are values passed to a function when it's called. Parameters are variables listed in the function definition's parentheses that receive these arguments.

The 'return' statement sends a value back from a function to the calling code.

The 'return' statement exits a function and sends a specified value back to the point where the function was called. Code after 'return' within the function is not executed.

Global variables are accessible anywhere; local variables are restricted to the function where they are defined.

Global variables, defined outside functions, are accessible everywhere. Local variables, defined inside functions, are only accessible within that specific function's scope. Avoid making local variables global unless necessary.

Use the 'global' keyword to modify a local variable outside its function's scope (use with caution).

The 'global' keyword allows a local variable to be accessed and modified from outside its defining function. Use this cautiously as it can lead to unexpected behavior and bugs.


Data Structures

Lists are ordered, mutable collections storing various data types, accessed by index.

Lists are ordered, mutable collections storing items of potentially different data types. Items are accessed using numerical indices starting from 0. They can be modified (add, remove, change elements) after creation.

Access list items using square brackets and zero-based indexing (e.g., my_list[0]).

List items are accessed using square brackets '[]' with their index number. Indexing starts at 0 for the first item.

Loop through lists using 'for item in my_list:' to process each element.

Iterate through all elements of a list using a 'for' loop: 'for item in my_list:'. Each element is assigned to 'item' successively.

List methods like '.append()', '.insert()', '.remove()', '.pop()', '.clear()', '.index()', '.count()', '.sort()', and '.copy()' manipulate list contents.

Common list methods include: '.append(item)' adds to the end, '.insert(index, item)' adds at specific index, '.remove(value)' removes first occurrence, '.pop(index)' removes and returns item at index (or last if index omitted), '.clear()' removes all items, '.index(value)' returns index, '.count(value)' returns occurrences, '.sort()' sorts in place, and '.copy()' creates a shallow copy.

Tuples are ordered, immutable collections, defined with parentheses and accessed by index.

Tuples are similar to lists but are immutable, meaning their contents cannot be changed after creation. They are defined using parentheses '()' and are indexed starting from 0.

To modify a tuple, convert it to a list, perform changes, then convert it back to a tuple.

Since tuples are immutable, modification requires converting the tuple to a list using 'list()', making changes, and then converting it back to a tuple using 'tuple()'.

Use 'len(tuple)' to find the number of items in a tuple.

The 'len(tuple)' function returns the number of elements contained within a tuple.

Dictionaries store data as key-value pairs, offering fast lookups via keys.

Dictionaries store data in key-value pairs (e.g., {'name': 'Alice'}). Keys must be unique and immutable (like strings or numbers), while values can be of any data type. They allow fast data retrieval using keys.

Access dictionary values using their keys: 'my_dict['key']'.

Retrieve a value from a dictionary by specifying its corresponding key within square brackets: 'my_dict['key']'.

Dictionary methods include '.keys()', '.values()', and '.items()' for accessing components.

'.keys()' returns a view object of all keys. '.values()' returns a view object of all values. '.items()' returns a view object of key-value tuple pairs.

Use '.update()', '.pop()', '.popitem()', and '.clear()' to modify dictionaries.

'.update(other_dict)' merges another dictionary's items. '.pop(key)' removes and returns the value for a key. '.popitem()' removes and returns the last key-value pair. '.clear()' removes all items.

Loop through dictionaries using '.keys()', '.values()', or '.items()' for iteration.

Iterate through a dictionary's keys using 'for key in my_dict.keys():'. Iterate through values using 'for value in my_dict.values():'. Iterate through both keys and values using 'for key, value in my_dict.items():'.

Sets store unique, unordered items and automatically discard duplicates.

Sets are unordered collections of unique items. They automatically remove duplicate elements upon creation or addition. Sets are mutable (elements can be added/removed) but do not support indexing.

Use '{'item1', 'item2'}' or 'set([item1, item2])' to create sets.

Create sets using curly braces ' { } ' with items separated by commas, or by passing an iterable (like a list) to the 'set()' function.

Set methods include '.add()', '.update()', '.remove()', '.discard()', '.pop()', '.clear()', '.union()', and '.intersection()'.

Common set methods: '.add(item)' adds one element. '.update(iterable)' adds multiple elements. '.remove(item)' removes item (error if not found). '.discard(item)' removes item (no error if not found). '.pop()' removes arbitrary element. '.clear()' removes all elements. '.union(other_set)' combines unique elements. '.intersection(other_set)' finds common elements.

'union()' combines elements from multiple sets, removing duplicates; 'intersection()' finds common elements.

'set1.union(set2)' returns a new set containing all unique elements from both set1 and set2. 'set1.intersection(set2)' returns a new set containing only elements present in both set1 and set2.


String and File Operations

Use '.split(delimiter)' to break a string into a list based on a separator.

The '.split(delimiter)' method breaks a string into a list of substrings. The 'delimiter' specifies the character(s) where the split occurs. If omitted, it splits by whitespace.

Use 'delimiter.join(list)' to combine list elements into a single string with a specified separator.

The 'delimiter.join(list)' method concatenates elements of a list into a single string, using the 'delimiter' string to separate each element. It is the inverse of '.split()'.

The OS module provides functions for interacting with the operating system, like managing files and directories.

The OS module offers functions for interacting with the operating system, such as getting the current working directory ('os.getcwd()'), listing directory contents ('os.listdir()'), changing directories ('os.chdir()'), creating directories ('os.mkdir()', 'os.makedirs()'), removing files ('os.remove()'), and removing directories ('os.rmdir()', 'os.removedirs()').

Use 'os.path.exists()' to check if a file or directory exists.

The 'os.path.exists(path)' function returns True if the specified file or directory path exists, and False otherwise. It checks for both files and directories.

Handle file operations safely using the 'with open(...) as file:' statement for automatic closing.

The 'with open(...) as file:' statement ensures files are automatically closed after use, even if errors occur. This simplifies resource management and prevents potential issues from unclosed files.

Open files in 'w' (write), 'r' (read), or 'a' (append) modes.

File opening modes: 'w' (write, creates file if it doesn't exist, truncates if it does), 'r' (read, file must exist), 'a' (append, adds to the end, creates if it doesn't exist).

Use file.write() to write a string to a file and file.writelines() to write a list of strings.

'file.write(string)' writes a single string to the file. 'file.writelines(list_of_strings)' writes multiple strings from a list. Add '\n' for new lines.

Read file content using file.read() (all content), file.readline() (one line), or file.readlines() (list of lines).

'file.read()' reads the entire file content as a single string. 'file.readline()' reads one line at a time. 'file.readlines()' reads all lines into a list, including newline characters.

'str.splitlines()' removes newline characters often included when reading lines from files.

The '.splitlines()' string method splits a string at line breaks and returns a list of lines, effectively removing the newline characters ('\n') that are often present when reading from files.

The shutil module offers advanced file operations like copying ('shutil.copy'), copying trees ('shutil.copytree'), moving ('shutil.move'), and removing directories with contents ('shutil.rmtree').

The 'shutil' module provides higher-level file operations. Key functions include: 'shutil.copy(src, dst)' copies a file, 'shutil.copytree(src, dst)' copies an entire directory tree, 'shutil.move(src, dst)' moves a file or directory, and 'shutil.rmtree(path)' removes a directory and all its contents.


Error Handling

Runtime errors (exceptions) crash programs; use try/except blocks to handle them gracefully.

Runtime errors (exceptions) halt program execution. The 'try' block contains code that might raise an error, and the 'except' block handles the error if it occurs, preventing the program from crashing.

The 'try' block encloses code that might cause an error.

The 'try' block contains the code segment that Python will attempt to execute. If an error occurs within this block, the execution is immediately transferred to the 'except' block.

The 'except' block catches and handles specific or general runtime errors.

The 'except' block executes if an error occurs in the 'try' block. You can specify the type of error to catch (e.g., 'except ZeroDivisionError:') or use a general 'except:' to catch any error. Errors are often stored in a variable (e.g., 'as e') for inspection.

Catch specific exceptions (e.g., ZeroDivisionError, FileNotFoundError) for targeted error handling.

Catching specific exceptions like 'ZeroDivisionError' or 'FileNotFoundError' allows for more precise error handling tailored to the potential problem, rather than catching all errors indiscriminately.

The 'else' block with try/except executes only if the 'try' block completes without errors.

The optional 'else' block executes only if the 'try' block runs successfully without raising any exceptions. It's useful for code that should run only when the 'try' block is error-free.

The 'finally' block always executes, regardless of whether an error occurred or not.

The optional 'finally' block always executes, whether an exception occurred in the 'try' block or not. It's typically used for cleanup actions like closing files or releasing resources.

Handle user input errors robustly, as user inputs are unpredictable.

User input can be unpredictable (e.g., entering '0' for division, non-numeric values). Exception handling is crucial to manage these input errors gracefully and prevent program crashes.


Networking

The 'socket' module enables network communication, allowing programs to send and receive data over the internet.

The 'socket' module provides tools for network programming, enabling systems to communicate. It supports protocols like TCP and UDP for exchanging data and interacting with network services.

Create a socket object using 'socket.socket(socket.AF_INET, socket.SOCK_STREAM)' for IPv4 TCP connections.

Use 'socket.socket(socket.AF_INET, socket.SOCK_STREAM)' to create a socket object for IPv4 (AF_INET) communication using the reliable TCP protocol (SOCK_STREAM).

Establish a connection to a remote host using 'socket.connect((host, port))'.

The 'socket.connect((host, port))' method attempts to establish a TCP connection to a specified 'host' on a given 'port'. It requires the host and port as a tuple.

Use 'socket.settimeout(seconds)' to limit connection attempts and prevent programs from hanging.

Set a connection timeout using 'socket.settimeout(seconds)'. If a connection cannot be established within the specified time, the program will proceed instead of freezing.

Use 'socket.gethostbyname(domain)' to retrieve the IPv4 address of a domain name.

The 'socket.gethostbyname(domain)' function performs DNS resolution, returning the IPv4 address associated with a given domain name. It raises an error (socket.gaierror) if the domain is invalid or unreachable.

Check internet connectivity by attempting to connect to a reliable host (e.g., Google) on a standard port (e.g., 443).

To check internet connectivity, try connecting to a known, stable host like Google on its standard HTTPS port (443). If the connection fails (caught by 'except socket.error'), the system is likely offline.

Use 'try...except socket.error' to handle network connection failures gracefully.

Wrap network operations (like connection attempts) in a 'try...except socket.error:' block to gracefully handle potential connection failures, informing the user if the connection couldn't be established.

'socket.gethostbyname()' uses DNS resolution in the background to translate domain names to IP addresses.

Behind the scenes, 'socket.gethostbyname()' utilizes the Domain Name System (DNS) protocol to translate human-readable domain names into machine-readable IP addresses.


Projects

Build a password generator that creates strong, customizable passwords using random characters.

A password generator program allows users to specify desired password length. It utilizes the 'random' module to select characters from a predefined set (letters, numbers, special symbols) and concatenates them to form a strong password.

Implement input validation to ensure password length meets minimum security requirements (e.g., 8 characters).

Validate user input for password length. If the entered length is below a security threshold (e.g., 8 characters), prompt the user again or exit the program gracefully using 'exit()'.

Return generated passwords from functions for better code organization and reusability.

Define a function (e.g., 'pass_gen') that generates the password and uses 'return' to send the generated password back to the calling code, allowing it to be stored in a variable and printed or used elsewhere.

Create a MAC address generator that produces valid MAC addresses using hexadecimal characters and hyphens.

A MAC address generator program creates random MAC addresses. It uses the 'random' module to select hexadecimal characters (0-9, A-F) and arranges them into six pairs separated by hyphens (e.g., 'AA-BB-CC-DD-EE-FF').

Format MAC addresses by inserting hyphens after every two hexadecimal digits.

To format a MAC address, iterate through the generated hexadecimal digits. After every pair of digits, append a hyphen ('-') to the string. Reset a counter after appending the hyphen to track the next pair.

Save generated MAC addresses to a file ('MAC_addresses.txt') using append mode ('a').

Write generated MAC addresses to a file using the 'with open('MAC_addresses.txt', 'a') as file:' statement. Each address is written on a new line using 'file.write(mac + '\n')' to append.

Build an interactive calculator program accepting user input for numbers and operations.

A calculator program prompts the user for two numbers and their desired operation (add, subtract, multiply, divide, modulus). It uses conditional statements ('if', 'elif', 'else') to perform the selected calculation.

Create separate functions for each arithmetic operation (add, subtract, multiply, divide, modulus) for modularity.

Define individual functions for each operation (e.g., 'add(a, b)', 'subtract(a, b)'). This makes the code modular and easier to manage. Pass user input numbers as arguments to these functions.

Use 'try-except' blocks to handle potential errors like division by zero or invalid user input.

Implement 'try-except' blocks when performing calculations, especially division. Catch specific errors like 'ZeroDivisionError' or general 'Exception' to handle invalid inputs or operations gracefully and prevent program crashes.

Implement network connectivity checks by attempting to connect to a reliable host like Google.

Check internet connectivity by using the 'socket' module to attempt a connection to a stable host (e.g., google.com on port 443). Use 'try-except socket.error' to determine if the connection succeeds ('online') or fails ('offline').

Use 'socket.gethostbyname(domain)' to resolve domain names to their corresponding IPv4 addresses.

The 'socket.gethostbyname(domain)' function resolves a domain name (like 'google.com') to its IP address. This is useful for validating domain existence or obtaining IP details.


Ask a Question

*Uses 1 Wisdom coin from your coin balance

Watch Video

Open in YouTube
WisdomEye Avatar
Got a minute?