Introduction Python

Python is a high-level, interpreted programming language known for its readability, simplicity, and wide range of applications. Created by Guido van Rossum and first released in 1991, Python emphasizes code readability and allows developers to express concepts in fewer lines of code compared to languages like C++ or Java.

Code Snippet print("Hello, World!")
Installing Python

Python can be installed on different operating systems, including Windows, macOS, and Linux. The official Python website provides installers and packages for each platform.

Installation Steps:

Windows:
macOS
Linux
Code Snippet sudo ./<installer_filename>.sh

Replace `<installer_filename>` with the name of the downloaded installer.

Windows and macOS
Code Snippet python --version
Linux
Code Snippet python3 --version

Python comes with a standard library, but you may need additional packages for your projects. You can install packages using the package manager pip.

Example:

To install the requests package, run the following command:

Code Snippet pip install requests

Virtual environments allow you to create isolated environments for different projects, each with its own dependencies.

Install "virtualenv" (Optional)
Code Snippet pip install virtualenv
Install "virtualenv" (Optional)
Code Snippet virtualenv myenv
Activate the Virtual Environment

Run the following commands based on your Operating software

Code Snippet myenv\Scripts\activate Code Snippet source myenv\bin\activate

Installing Python is a simple process that involves downloading the installer from the official website and running it on your system. Once installed, you can start writing and executing Python code. Additionally, you can use package managers like "pip" to install additional packages and create virtual environments to manage dependencies for different projects.

Variables and Data Types

Variables

A variable in Python is a reserved memory location used to store data values. Unlike other programming languages, Python does not require explicit declaration of variables before their use.

Code Snippet x = 5
y = "Hello, World!"

Data Types

Code Snippet # Numeric Types
x = 5 # int
y = 3.14 # float

# Sequence Types
name = "Python"            # str
my_list = [1, 2, 3]        # list
my_tuple = ('a', 'b', 'c') # tuple

# Mapping Type
person = {'name': 'John', 'age': 30} # dict
# Set Type

my_set = {1, 2, 3} # set
# Boolean Type

is_valid = True    # bool

You can convert between different data types using built-in functions like "int()", "float()", "str()", "list()", "tuple()", "dict()", and "set()".

Code Snippet # Convert int to float
x = float(5)

# Convert float to int
y = int(3.14)

# Convert int to string
z = str(5)

Understanding variables and data types is fundamental in Python programming. Python provides a rich set of built-in data types to handle various types of data, making it a versatile language suitable for a wide range of applications.

Conditional Statements

Introduction

Conditional statements in Python allow you to execute different blocks of code based on whether a specified condition evaluates to True or False. The two primary conditional statements in Python are the if-else statement and the if statement.

1. if-else Statement

Code Snippet if condition:
    # Code block to execute if condition is True
else:
    # Code block to execute if condition is False

Code Snippet x = 5
if x > 0:
    print("x is positive")
else:
    print("x is non-positive")

2. if Statement (without else)

Code Snippet if condition:
    # Code block to execute if condition is True

Code Snippet x = 5
if x > 0:
    print("x is positive")

3. Nested if-else Statements

You can nest "if-else" statements within each other to handle multiple conditions.

Code Snippet x = 5
if x > 0:
    print("x is positive")
else:
    if x == 0:
        print("x is zero")
    else:
        print("x is negative")

Multiple Conditions with "elif"

You can use the "elif" keyword to specify additional conditions in between the "if" and "else" statements.

Code Snippet x = 5
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

Conditional statements in Python provide a way to execute different blocks of code based on specified conditions. Whether you need to perform simple or complex decision-making in your program, if-"else" and "if" statements give you the flexibility to handle various scenarios.

Loops for and while

Introduction

Loops in Python provide a way to execute a block of code repeatedly. Python supports two main types of loops: the "for" loop and the "while" loop. Each type of loop serves different purposes and can be used to solve various programming problems efficiently.

1. "for" Loop

Code Snippet for variable in iterable:
    # Code block to execute

  • The "for" loop iterates over each item in the iterable (such as a list, tuple, string, or range).
  • For each iteration, the loop assigns the current item to the "variable" and executes the code block.

  • Code Snippet # Iterating over a list
    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
        print(num)

    The range"()" function generates a sequence of numbers, which is often used with "for" loops.

    Example:

    Code Snippet # Printing numbers from 0 to 4
    for i in range(5):
        print(i)

    2. "while" Loop

    Code Snippet while condition:
        # Code block to execute

    Code Snippet # Printing numbers from 0 to 4 using a while loop
    i = 0
    while i < 5:
        print(i)
        i += 1

    Loop Control Statements

    Python provides several control statements that allow you to modify the behavior of loops.

    The "break" statement terminates the loop prematurely.

    Example:

    Code Snippet # Using break to exit the loop when a condition is met
    for i in range(10):
        if i == 5:
            break
        print(i)

    The "continue" statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.

    Example:

    Code Snippet # Using continue to skip an iteration when a condition is met
    for i in range(10):
        if i % 2 == 0:
            continue
        print(i)

    Both "for" and "while" loops can have an "else" clause, which executes after the loop completes normally (i.e., not terminated by "break").

    Example:

    Code Snippet # Using else with a for loop
    for i in range(5):
        print(i)
    else:
        print("Loop completed normally")

    # Using else with a while loop
    i = 0
    while i < 5:
        print(i)
        i += 1
    else:
        print("Loop completed normally")

    Loops can be nested within each other, allowing you to perform more complex iterations.

    Example

    Code Snippet # Nested for loop
    for i in range(3):
        for j in range(2):
            print(f"i: {i}, j: {j}")

    Conclusion

    Loops are a fundamental aspect of Python programming, providing a mechanism to repeat tasks efficiently. The "for" loop is ideal for iterating over sequences, while the "while" loop is suited for repeated execution as long as a condition holds true. Loop control statements ("break", "continue", "else") offer additional flexibility, allowing you to manage loop execution flow more precisely. Nested loops enable the execution of complex iterations, making Python loops a powerful tool for various programming tasks.

    Exceptions Handling

    Introduction

    Exception handling in Python provides a way to manage errors and exceptional conditions that may occur during the execution of a program. By using exception handling, you can ensure your program continues to operate under unexpected conditions and can handle errors gracefully.

    Basics of Exception Handling

    An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. When an error occurs, Python generates an exception, which can be handled using the "try" and "except" blocks.

    Code Snippet try:
    # Code that might raise an exception
    except ExceptionType:
    # Code to handle the exception

    Code Snippet try:
        result = 10 / 0
    except ZeroDivisionError:
        print("You can't divide by zero!")

    Handling Multiple Exceptions

    You can handle multiple exceptions by specifying different except blocks for each exception type.

    Code Snippet try:
    # Code that might raise multiple exceptions
    except ExceptionType1:
        # Code to handle ExceptionType1
    except ExceptionType2:
        # Code to handle ExceptionType2

    Code Snippet try:
         value = int(input("Enter a number: "))
         result = 10 / value
    except ValueError:
         print("That's not a valid number!")
    except ZeroDivisionError:
         print("You can't divide by zero!")

    The "else" clause

    The "else" clause can be used to execute code if no exceptions were raised in the "try" block.

    Code Snippet try:
         # Code that might raise an exception
    except ExceptionType:
         # Code to handle the exception
    else:
         # Code to execute if no exception occurs

    Code Snippet try:
         result = 10 / 2
    except ZeroDivisionError:
         print("You can't divide by zero!")
    else:
         print("Division successful:", result)

    The "finally" Clause

    The "finally" clause can be used to specify a block of code that will be executed no matter what, whether an exception was raised or not.

    Code Snippet try:
         # Code that might raise an exception
    except ExceptionType:
         # Code to handle the exception
    finally:
         # Code to execute no matter what

    Code Snippet try:
         result = 10 / 2
    except ZeroDivisionError:
         print("You can't divide by zero!")
    finally:
         print("This will execute no matter what.")

    Raising Exceptions

    You can raise exceptions using the "raise" keyword. This can be useful to signal that an error has occurred.

    Code Snippet raise ExceptionType("Error message")
    Code Snippet def check_positive(number):
        if number < 0:
            raise ValueError("The number must be positive.")
        return number

    try:
        check_positive(-10)
    except ValueError as e:
        print(e)

    Custom Exceptions

    You can create custom exception classes to handle specific errors in your program. Custom exceptions should inherit from the base "Exception" class.

    Code Snippet class CustomError(Exception):
        pass

    try:
        raise CustomError("This is a custom error.")
    except CustomError as e:
        print(e)

    Conclusion

    Exception handling in Python is a powerful mechanism to manage errors and exceptional conditions gracefully. By using "try", "except", "else", and "finally" blocks, you can ensure that your program can handle unexpected situations and continue to function correctly. Additionally, you can raise exceptions and create custom exceptions to handle specific errors in your applications.