Python 101
Python Programming Essentials
Description:
This Tutorial introduces the fundamentals of Python programming, encompassing basic to intermediate concepts. To learn and understand about Python operations, package management, object-oriented programming, and more.
Prerequisites:
Basic understanding of computer operations
Familiarity with any programming language is helpful but not mandatory
What is Python?
Python is a general-purpose programming language that is interpreted, high-level, and dynamically typed. It is designed to be easy to read and write. Python is popular because it is versatile, has a large community, and is used for a wide variety of applications.
Python 2 vs. Python 3
Python 2 is the older version of the language, and it is still widely used. However, Python 3 is the newer version, and it is the recommended version to use. Python 3 has a number of improvements over Python 2, including:
It is more secure. Python 3 has a number of security features that are not present in Python 2.
It is more consistent. Python 3 has a more consistent syntax and semantics than Python 2.
It is more future-proof. Python 3 is the future of the language, and it is the version that is being developed by the Python community.
Setting up the Python environment
To set up the Python environment, you will need to:
Download and install the Python interpreter.https://www.python.org/downloads/
Create a new project directory.
Open a terminal window in the project directory.
Type the following command to create a new Python file:
Variables and Data Types
Variables are names that refer to values. Python is dynamically-typed, which means you don't declare variable types explicitly.
Basic Operators and Operands
Python supports various types of operators, which are used to perform operations on values and variables. Here are some basic arithmetic operators:
Operators are the constructs which can manipulate the value of operands. Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
String Manipulation
String manipulation is one of Python's strengths. Here's some common string manipulation:
Accepting User Inputs
Python allows for user input via the input() function:
Basic I/O Operations
Reading from and writing to files is a common task in Python programming.
The with statement automatically takes care of closing the file once it leaves the block, even in cases of error. I/O operations should always be done carefully to handle potential exceptions such as file not found errors.
Python Control Structures
Control structures in Python determine the flow of program execution based on conditions and loops.
Indentation in Python
Indentation is crucial in Python and is used to define the blocks of code. Consistent spacing is key.
Conditional Statements
Conditional statements allow for branching in code execution based on conditions.
If Statement
The if
statement is used to execute a block of code if a condition is true.
Elif Statement
The elif
(else if) statement is used to check multiple expressions for True
and execute a block of code as soon as one of the conditions evaluates to True
.
Else Statement
The else
statement is used to execute a block of code if none of the preceding conditions are true.
Logical Operators
Logical operators are used to combine conditional statements:
and
: True if both operands are trueor
: True if either operand is truenot
: True if operand is false (complements the operand)
Loops
Loops are used for iterating over a sequence (such as a list, tuple, dictionary, set, or string).
For Loops
The for
loop is used to iterate over the elements of a sequence.
While Loops
The while
loop executes a set of statements as long as a condition is
Conditional Statements
Conditional statements allow for branching in code execution based on conditions.
If Statement
The if
statement is used to execute a block of code if a condition is true.
Elif Statement
The elif
(else if) statement is used to check multiple expressions for True
and execute a block of code as soon as one of the conditions evaluates to True
.
Else Statement
The else
statement is used to execute a block of code if none of the preceding conditions are true.
Logical Operators
Logical operators are used to combine conditional statements:
and
: True if both operands are trueor
: True if either operand is truenot
: True if operand is false (complements the operand)
Loops
Loops are used for iterating over a sequence (such as a list, tuple, dictionary, set, or string).
For Loops
The for
loop is used to iterate over the elements of a sequence.
While Loops
The while
loop executes a set of statements as long as a condition is true.
Break and Continue
break
and continue
are used inside loops to alter their normal behavior.
Break
Python Control Structures
Control Structures
Python control structures manage the flow of your code's execution. There are two main types: conditional statements and loops.
Indentation in Python
Python uses indentation to define blocks of code. All code within the same block must have the same indentation.
Conditional Statements (if, elif, else)
Conditional statements allow you to execute different blocks of code depending on various conditions.
Logical Operators
Logical operators are used to combine conditional statements.
and
: Both conditions must be trueor
: At least one condition must be truenot
: Inverts the truth value
Loops (for and while loops)
Loops are used for iterating over a sequence (like a list, tuple, or string) or executing a block of code multiple times.
For Loops
For loops iterate over each item in a sequence.
While Loops
While loops repeat as long as a certain boolean condition is met.
Break and Continue
break
and continue
control the flow of loops.
break
: Exit the loop immediatelycontinue
: Skip the rest of the code inside the loop for the current iteration and move on to the next iteration
Remember, these are just the basic structures. Python offers more complex control structures and features that you can explore as you become more comfortable with the language.
Data Collections in Python
Python provides several data structures for storing and manipulating collections of data. Understanding these collections is vital for efficient Python programming.
Lists
A list in Python is an ordered collection of items which can be modified (mutable). Lists are defined using square brackets []
and can contain items of different types.
Data Collections in Python
In Python, there are several built-in data types that can be used to group multiple data together, known as collections. Among these are lists, tuples, sets, and dictionaries. Understanding how to create and iterate over these collections is fundamental in Python programming.
Lists
A list is an ordered collection of items that are mutable, meaning we can modify them after their creation. Lists are created by placing all the items (elements) inside square brackets []
, separated by commas.
Example of List Operations:
Tuples are similar to lists, but they are immutable, meaning they cannot be changed after they are created. Tuples are defined using parentheses ().
Sets
A set is an unordered collection of items where every element is unique (no duplicates). Sets are defined using curly braces {}.
A dictionary in Python is an unordered collection of data in a key:value pair form. A collection of such pairs is enclosed in curly braces {}.
iteration over Collections
You can iterate over the elements of a collection using a loop. For dictionaries, you can iterate over the keys, values, or key:value pairs.
Functions in Python
Functions are one of the most important constructs in Python. They allow you to create blocks of code that can be easily executed multiple times, without needing to rewrite the code.
Defining Functions
A function is defined using the def
keyword, followed by a function name with parentheses and a colon. The indented block of code following the :
is executed each time the function is called.
Example of Function Definition:
Scope of Variables
Variables defined within a function have a local scope, meaning they can only be accessed within the function. Variables defined outside of any function have a global scope, and can be accessed anywhere in the code.
#Lambda Functions Lambda functions are small anonymous functions defined with the lambda keyword. They can take any number of arguments, but can only have one expression.
#Modules and Importing A module is a file containing Python code that can define functions, classes, and variables. These modules can then be imported into other Python programs.
When you import a module, Python looks at several places defined in sys.path. It is a list of directory locations.
Using the from Keyword
You can also use the from keyword to import specific functions, classes, or variables from a module.
Python Packages and PIP
Python packages and the Python Package Installer (PIP) are fundamental tools for any Python developer. They enable you to easily use and manage additional libraries and dependencies in your Python projects.
What are Python Packages?
A Python package is a collection of Python modules under a common namespace. In simpler terms, it's a directory that contains a special file named __init__.py
and can include other modules and subpackages. Packages allow for a hierarchical structuring of the module namespace using dot notation. For example, a package named my_package
could have a module named my_module
accessible as my_package.my_module
.
Example of a Python Package:
my_package/ init.py
my_module.py sub_package/ init.py another_module.py
Here, my_package
is a Python package containing a module my_module
and a subpackage sub_package
with a module another_module
.
Introduction to PIP (Python Package Installer)
PIP is a package management system used to install and manage software packages written in Python. It connects to an online repository of public packages, called the Python Package Index (PyPI), to download and install packages.
Features of PIP:
Installing Python packages from PyPI.
Managing package versions.
Listing installed packages.
Uninstalling packages.
Installing Packages with PIP
To install a package using PIP, you use the command pip install package_name
. PIP downloads the
package from PyPI and installs it in your Python environment.
Managing Package Versions
PIP allows you to specify the version of a package you want to install. You can also upgrade or downgrade a package to a specific version.
vritual Environment
Virtual environments in Python are a tool to keep dependencies required by different projects in separate places. They solve the "Project X depends on version 1.x but, Project Y needs 4.x" dilemma and keep your global site-packages directory clean and manageable.
File Operations in Python
Working with files is a common task in many programming projects. Python provides straightforward methods to handle files, which include reading from and writing to files, managing file paths, and handling exceptions.
Reading from and Writing to Files
Python allows you to read content from a file and write content to a file. This is commonly done using the built-in open()
function.
Reading from a File:
This opens example.txt in read mode ('r'), reads its content into the variable content, and then closes the file.
File Paths, Opening and Closing Files
When working with files, you need to provide the file path, which can be an absolute or relative path.
Example of File Paths:
Absolute Path: /users/example/documents/example.txt
Relative Path: documents/example.txt
Opening and Closing Files:
Files should always be closed after their operations are completed to free up system resources.
Working with File Modes
File modes determine the actions you can perform on the file, like reading, writing, or appending.
'r' - Read mode
'w' - Write mode
'a' - Append mode
'r+' - Read and write mode
Handling File Exceptions
The Context Managers (with statement)
The with
statement in Python simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. For file operations, it ensures that the file is properly closed after its suite finishes, even if an exception is raised.
Example of Reading with a Context Manager:
The self parameter
self
represents the instance of the class. It's used to access variables that belong to the class.
The init method and Constructors
__init__
is a special method called a constructor, used to initialize a newly created object’s attributes.
Class Methods, Instance Methods, and Static Methods
Instance Methods: Take
self
as the first argument and relate to a specific instance of the class.Class Methods: Take
cls
as the first argument and can access class variables but not instance variables.Static Methods: Do not take
self
orcls
as the first argument and behave like regular functions, but belong to the class's namespace.
Inheritance and Polymorphism
Inheritance: Allows a new class to inherit attributes and methods from an existing class.
Polymorphism: Refers to the way in which different object classes can share the same method name, but those methods can act differently based on which object calls them.
This provides an overview of the key concepts of Object-Oriented Programming in Python, which is a powerful paradigm for structuring and organizing code, especially in large programs or when dealing with complex data models.
In this example:
A
PortScanner
class is defined with methods for scanning TCP and UDP ports.An object
scanner
is created from thePortScanner
class.The
perform_scan
method is called on thescanner
object to perform the port scanning.
Please Note:
UDP scanning is unreliable using this method, as UDP is connectionless and doesn't respond with errors like TCP.
Scanning networks without permission can be illegal and unethical. Always obtain explicit authorization before scanning any network or system.
The script's performance can be improved with multithreading or asynchronous I/O, but this simple version is for demonstration purposes.
Error Handling in Python
Error handling in Python is managed through the use of exceptions. Exceptions are a way of signaling error conditions in a program. Python provides several built-in exceptions, but also allows the creation of custom exceptions.
Basic Exception Handling
Exception handling in Python is done through the use of try
and except
blocks.
Try Block: Encloses the code that might throw an exception.
Except Block: Handles the exception if one occurs in the try block.
Finally Block
The finally
block is optional and is executed regardless of whether an exception is raised or not. It's typically used for clean-up code.
Raising Exceptions
You can raise exceptions using the raise
statement. This is useful for throwing custom errors or re-raising caught exceptions.
Creating Custom Exceptions
Custom exceptions can be created by defining a new class that inherits from the base Exception
class.
Understanding and properly implementing error handling in Python can greatly improve the reliability and
robustness of your code, allowing for more graceful handling of unexpected situations and better user experiences.
Dictionary Comprehensions: Similar to list comprehensions, but for dictionaries.
Set Comprehensions: Used for creating sets in a concise way.
Iterators and Generators
Iterators: Objects that can be iterated over.
Generators: Simple way to create iterators using functions and the
yield
keyword.
Decorators
Decorators are a powerful way to modify
the behavior of functions or classes.
Advanced Modules
Python provides a vast standard library that includes several advanced modules:
os: Interacting with the operating system.
sys: Accessing variables used or maintained by the interpreter and functions that interact strongly with the interpreter.
json: Working with JSON data.
datetime: Handling date and time.
Python Packages
Requests
Last updated
Was this helpful?