Tag: Python

  • Python Decision Making and Loops

    Control Flow

    Control Flow in Python refers to the order in which the statements and instructions in a Python program are executed. By default, Python executes code sequentially from top to bottom, but control flow structures allow you to make decisions, repeat actions, or change the execution path based on conditions. The main control flow tools in Python include:


    Logical Expression

    Logical Expression is a statement that can either be true or false. The following are some of the comparison operators:

    1 > 2 is 1 bigger than 2 (Result is False)
    1 < 2 is 1 smaller than 2 (Result is True)
    1 == 2 is 1 equal to 2 (Result is False)
    1 != 2 is 1 not equal to 2 (Result is True)
    1 => 2 is 1 is equal or bigger than 2 (Result is False)
    1 <= 2 is 1 is equal or smaller than 2 (Result is True)

    Example

    if 100 > 99: # Condition: if 100 is greater than 99 (True)
        print(“Good!”) # Since the condition is True, print “Good!”

    if 100 > 99:
    print("Good!")

    Result

    Good!

    Logical Operators

    Logical Operators are used to connect\combine multiple logical expressions. The following are some of the logical operators:

    1 == 1 and 2 == 2 is True because both statement are True
    1 == 1 and 1 == 2 is False because only one statement is True
    1 == 1 or 1 == 2 is True one of the statements is True
    1 == 2 or 1 == 2 is False because neither statements is True

    Example

    if 100 > 99 and 99 == 99: # Both conditions must be True for the code inside to execute
        print(“Good!”) # Both conditions are True, so “Good!” is printed

    if 100 > 99 and 99 == 99:
    print("Good!")

    Result

    Good!

    if Statement

    if keyword executes a block of code when a logical condition is met. if statement is one of the most well-known statement types. The if statement usually ends with :, and the block of code after the if a statement is indented.

    Example

    if 1 == 1: # Condition evaluates to True
        print(“Good!”) # Since the condition is True, print “Good!”

    if 1 == 1:
    print("Good!")

    Result

    Good!

    Or, you can do that without indentation

    Example

    if True: print(“Good!”)  # Condition evaluates to True, since the condition is True, print “Good!”

    if True:print("Good!")

    Result

    Good!

    if … elif Statement

    ifelif keywords are used to check for multiple logical conditions.

    Example

    temp_value = 1 # Assign the value 1 to the variable temp_value
    if temp_value == 1: # If temp_value equals 1
        print(“Value is 1”) # Print this message
    elif temp_value == 2: # Otherwise, if temp_value equals 2
        print(“Value is 2”) # Print this message
    elif temp_value == 3: # Otherwise, if temp_value equals 3
        print(“Value is 3”) # Print this message

    temp_value = 1

    if temp_value == 1:
    print("Value is 1")
    elif temp_value == 2:
    print("Value is 2")
    elif temp_value == 3:
    print("Value is 3")

    Result

    Value is 1

    Now, change temp_value to 2 and try again

    Example

    temp_value = 2 # Assign the value 2 to the variable temp_value
    if temp_value == 1: # If temp_value equals 1
        print(“Value is 1”) # Print this message
    elif temp_value == 2: # Otherwise, if temp_value equals 2
        print(“Value is 2”) # Print this message
    elif temp_value == 3: # Otherwise, if temp_value equals 3
        print(“Value is 3”) # Print this message

    temp_value = 2

    if temp_value == 1:
    print("Value is 1")
    elif temp_value == 2:
    print("Value is 2")
    elif temp_value == 3:
    print("Value is 3")

    Result

    Value is 2

    if … else Statement

    ifelse keywords are used to check for one logical condition, if not, then execute the block of code after the else statement

    Example

    if 1 == 2: # Condition is False
        print(“Value is 1”) # This line is skipped because the condition is False
    else: # Otherwise
        print(“Value is 2”) # Since the 1 == 2 condition is False, this line is executed

    if 1 == 2:
    print("Value is 1")
    else:
    print("Value is 2")

    Result

    Value is 2

    for Statement

    for keyword is used to iterate over a sequence (list, tuple, set, dict or, string) and executes a block of code every iteration. The for statement usually ends with :, and the block of code after the for a statement is indented.

    Example

    for item in range(5): # range(5) generates numbers 0,1,2,3,4
        print(item) # Print the current value of item in each iteration

    for item in range(5):
    print(item)

    Result

    0
    1
    2
    3
    4

    Or, you can do that without indentation

    Example

    for item in range(5):print(item) # range(5) generates numbers 0,1,2,3,4, then print the current value of item in each iteration

    for item in range(5):print(item)

    Result

    0
    1
    2
    3
    4

    while statement

    while keyword is used to repeat executing a block of code as long as a condition is met. The while statement usually ends with :, and the block of code after the while a statement is indented.

    Example

    counter = 0 # Initialize a counter variable to 0
    while counter < 5: # Continue looping while counter is less than 5
        print(counter, “is less than 5”) # Print the current value of counter and message
        counter = counter + 1 # Increment counter by 1 in each iteration

    counter = 0

    while counter < 5:
    print(counter, "is less than 5")
       counter = counter + 1

    Result

    0 is less than 5
    1 is less than 5
    2 is less than 5
    3 is less than 5
    4 is less than 5

    break statement

    break keyword is used to break for or while loop

    Example

    while True: # Start an infinite loop
        break # Immediately exit the loop
        print(“Looping…”) # This line will never run because break exits the loop first

    while True:
    break
       print("Looping...")

    Result

     

    Nested statements

    You can nest statements (Remember to indent when you nest)

    Example

    for item in range(5): # Loop through numbers from 0 to 4
        if item == 2: # Check if the current item equals 2
            print(“Item”, item, “Found!”) # Print the item 2
            print(“Breaking the loop”, item) # Print a message before breaking
            break # Exit the loop immediately

    for item in range(5):
    if item == 2:
    print("Item", item, "Found!")
    print("Breaking the loop", item)
    break

    Result

    Item 2 Found!
    Breaking the loop 2
  • Python Basics

    Expression

    A combination of values (E.g. 5) and operators (E.g. +), which will be evaluated to a value

    Example

    9 * 98 # multiplies the numbers (result = 882)
    / 1 # divides by 1 (so the value stays 882)
    print() # displays the result in the console

    print(9*98/1)

    Result

    882.0

    Operators Precedence

    Is the order of operations (PEMDAS) – If you have multiple operations, E.g. (+ and /) in the same expression, the division will be evaluated first, then the addition because of the PEMDAS rule

    The order is:

    1. () Parentheses 
    2. ** Exponentiation
    3. * Multiplication
    4. / Division
    5. + Addition
    6. - Subtraction

    Statement

    An instruction that gets executed by the Python interpreter

    • Simple Statement is written in one line (It does simple operation)
      • break – Terminates the closest for or while loop
      • pass – Used as placeholder
      • del – Deletes object
      • import – Finds, loads and initializes a module
      • return – Sends the result of a function to a caller
      • continue – Ends the current iteration of a loop
    • Compound Statement
      • if – Executes a block of code based on a condition
      • while – An uncontrolled loop (Number of iterations is unknown)
      • for – A controlled loop (Number of iterations is known)
      • try – Used for exception handling

    Value

    The actual data, and Python has a few data types. We can store those data types in variables.


    Variable

    A container that stores values, it must start with a letter or the underscore symbol and contains alpha-numeric-underscore only (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012456789_).


    Some Data Types

    Data Type is an attribute that tells the computer system how to interpret its value. Computer systems use different data types and each data type has a fixed or not-fixed length. E.g, an Integer (int) is a common data type that represents numbers data without fractions, the size of int is fixed (4 bytes) in many systems. Some data types like Text (string) are not-fixed, but it has a max size like 65,535 bytes (Sometimes, data types with fixed sizes like Integer (int) can change based on the implementation)

    • int (Number)
      • 5
      • 61111
      • 7988787
    • float (Number)
      • 0.5
      • 0.841
      • 9.20000008884
    • bool
      • True
      • False
    • list (Ordered collection of items – mutable)
      • [1,2,3,4,’hello’]
    • tuple (Ordered collection of items – immutable)
      • (1,2,3,4,’hello’)
    • set (Unordered collection of items – no duplicates)
      • {1,2,3,4,’hello’}
    • dict (Collection of sequence key:value – no key duplicates)
      • {1:”test”,2:”test”}
    • string
      • ‘Hello’
      • “Hello”

    Mutable

    Something is changeable, whereas immutable is something we cannot change.


    Assign value to variable

    The assignment operator in Python is = symbol; Usually, the variable is on the left side, and the value is on the right side.

    Example

    var = 1 # Integer variable storing the number 1
    var20 = ‘python’ # String variable storing the text ‘python’
    var_99 = [1,2,3,4] # List variable containing four numbers
    VaR = {1,2,4,5} # Set variable containing unique numbers (unordered collection)

    print(var) # Print the value stored in variable ‘var’
    print(var20) # Print the string stored in ‘var20’
    print(var_99) # Print the list stored in ‘var_99’
    print(VaR) # Print the set stored in ‘VaR’

    var = 1
    var20 = 'python'
    var_99 = [1,2,3,4]
    VaR = {1,2,4,5}

    print(var)
    print(var20)
    print(var_99)
    print(VaR)

    Result

    1
    python
    [1,2,3,4]
    {1,2,4,5}

    Output & Input

    You can output data using the print function, and you can get the user’s data using the input function.

    Example

    temp_name = input(“Enter your name: “) # Prompt the user to type their name and store it in the variable temp_name
    print(“Your name is: ” + temp_name) # Concatenate the text “Your name is: ” with the value of temp_name and print it

    temp_name = input("Enter your name: ")
    print("Your name is: " + temp_name)

    Result

    Enter your name: Sara
    Your name is Sara

    Function

    A reusable block of code, you can define a function using the def statement, followed by the name of the function, then (): and the body has to be indented (spaces or tabs). To call the function, use the function name + ().

    Example

    def temp_function(): # Define a function named temp_function
        print(“Hello World”) # Print the message “Hello World”

    temp_function() # Call the function to execute its code

    def temp_function():
    print("Hello World")

    temp_function()

    Result

    Hello World

    Also, you can define a function that takes arguments using the def statement, followed by the name of the function, then add your parameters inside (): and the body has to be indented (spaces or tabs). To call the function, use the function name + the arguments inside ().

    Example

    def temp_function(param1): # Define a function named temp_function with one parameter called param1
        print(param1) # Print the value passed into param1

    temp_function(“Hello World!”) # Call the function and pass the string “Hello World!” as the argument

    def temp_function(param1):
    print(param1)

    temp_function("Hello World!")

    Result

    Hello World!

    Argument

    A value that are passed to a function when it is called.

    Example

    def temp_function(param_in): # Define a function with one parameter called param_in
        print(param_in) # Output the value stored in param_in

    temp_function(“Hello Jim”) # Call the function and pass “Hello Jim” as the argument

    def temp_function(param_in):
    print(param_in)

    temp_function("Hello Jim")

    Result

    Hello Jim

    Parameter

    The names of the data declared in the function’s parenthesis.

    Example

    def temp_function(param_in): # Define a function called temp_function with one parameter named param_in
        print(param_in) # Print the value passed into the parameter param_in

    temp_function(“Hello world”) # Call the function and pass the string “Hello world” as the argument

    def temp_function(param_in):
    print(param_in)

    temp_function("Hello world")

    Result

    Hello world

    Indentation

    This refers to the leading white-space (Spaces and tabs) at the beginning of the code.

    Example

    if 1 == 1: # Check if the value 1 is equal to 1 using the equality operator ==
        print(“True”) # If the condition is True, print the text “True”

    if 1 == 1:
    print("True")

    Result

    True

    Pass By Value

    Mutable objects are passed by values to function

    Example

    def change_value(param_in): # Define a function that takes one parameter called param_in
        param_in = param_in * 10 # Multiply param_in by 10 and store the result in the local variable param_in

    var = 10 # Create a variable var and assign it the value 10

    print(“Value before passing: “, var) # Print the value of var before calling the function
    change_value(var) # Call the function and pass var as an argument
    print(“Value after passing: “, var) # Print the value of var again (it remains unchanged)

    def change_value(param_in):
        param_in = param_in * 10

    var = 10

    print("Value before passing: ", var)
    change_value(var)
    print("Value after passing: ", var)

    Output

    Value before passing:  10
    Value after passing:  10

    Pass By Reference

    Immutable objects are passed by reference to function

    Example

    def change_value(param_in): # Define a function that takes one parameter called param_in
        param_in.append(99) # Append the number 99 to the list param_in (modifies the original list)

    var = [0, 1, 2, 3, 4, 5] # Create a list variable var with initial values

    print(“Value before passing: “, var) # Print the list before calling the function
    change_value(var) # Call the function and pass var; list is modified inside the function
    print(“Value after passing: “, var) # Print the list after function call; shows the updated list

    def change_value(param_in):
        param_in.append(99)

    var = [0,1,2,3,4,5]

    print("Value before passing: ", var)
    change_value(var)
    print("Value after passing: ", var)

    Output

    Value before passing:  [0, 1, 2, 3, 4, 5]
    Value after passing:  [0, 1, 2, 3, 4, 5, 99]

    Print function()

    The print function outputs a string representation of the object to the standard output. If the object contains __str__ method, it will be called by the print function 

    Example

    class string: # Define a class named string
        def __init__(self, var): # Constructor that initializes the object with a value var
            self.var = var # Store the value in the instance variable self.var

        def __str__(self): # Define string representation for printing
            return f'{self.var}’ # Return the value of self.var as a string

        def __eq__(self, other): # Define equality comparison between two string objects
            if isinstance(other, string): # Check if ‘other’ is an instance of string
                return self.var == other.var # Compare their stored var values
            return False # If other is not a string object, return False


    print(string(“test”) == string(“test”)) # Create two string objects, compare them and output the result

    class string:
        def __init__(self, var):
            self.var = var

        def __str__(self):
            return f'{self.self.var}'

        def __eq__(self, other):
            if isinstance(other, string):
                return self.var == other.var
            return False

    print(string("test") == string("test"))

    Output

    True
  • Python Introduction

    Python Introduction

    Computer Programming

    Computer Programming is the process of designing, creating, testing, and maintaining programs to perform specific tasks or solve particular problems. It involves translating logical solutions into a language computers can understand and execute. Programmers use languages like Python, Java, C++, or JavaScript to write code that instructs computers on how to carry out required operations.


    Python

    Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility. It was first released in 1991 as Python 0.9.0 by Guido van Rossum. Python is cross-platform, so it can run on various operating systems like Windows, macOS, and Linux without significant code changes.

    Python supports object-oriented programming, allowing developers to design software using objects that encapsulate data and behavior. It also supports procedural and functional programming paradigms, making it highly flexible. As an interpreted language, Python executes code line by line, which facilitates rapid development, easier debugging, and interactive testing.


    Interpreted (?)

    Interpreted refers to a method of program execution where the source code is not directly compiled into machine code beforehand. Instead, the code is executed line by line or in small sections at runtime, often through an interpreter.

    Interpretation Process

    1. Source Code: The programmer writes Python code in a human-readable form.
    2. Compilation to Bytecode: Before execution, Python automatically translates the source code into bytecode, which is a low-level, platform-independent representation of the code.
    3. Execution by the Python Virtual Machine (PVM): The PVM reads and executes the bytecode, translating it into machine-level instructions that the computer can understand.

    Advantages

    • Cross-Platform Compatibility: Since the bytecode is platform-independent, the same Python program can run on any system with a compatible Python interpreter.
    • Ease of Debugging: Errors are caught during runtime, making testing and debugging easier, especially for beginners.
    • Interactive Development: Python supports interactive execution, allowing developers to test code snippets immediately without compiling the entire program.

    Compiled

    Compiled refers to a method of program execution where the source code written by the programmer is directly translated into machine code by a compiler before the program is run. Machine code consists of low-level instructions that a computer’s processor can execute directly.

    Compilation Process:

    1. Source Code: The programmer writes human-readable code in a programming language such as C, C++, or Rust.
    2. Compilation: The compiler analyzes the source code, checks it for errors, and translates it into machine code specific to the target processor and operating system. This results in an executable file.
    3. Linking: If the program uses external libraries or modules, the compiler links them together with the machine code to create a complete, runnable program.
    4. Execution: The final executable file can be run directly by the computer without needing an interpreter.

    Advantages

    • Faster Execution: Compiled programs generally run faster because the code is already translated into machine language.
    • Platform-Specific: The resulting executable is usually specific to the operating system and processor architecture it was compiled for.
    • Error Detection: Compilation detects many errors before the program is run, which can make debugging easier.
    • No Runtime Translation: Unlike interpreted languages, compiled code does not require an interpreter to execute.

    Cross-Platform

    Cross-Platform refers to software, applications, or programming languages that can run on multiple operating systems or hardware platforms with minimal modification. This means the same program can function on Windows, macOS, Linux, and sometimes even mobile operating systems like Android or iOS.


    High-Level

    A High-Level Programming Language is designed to be human-readable and easy to use. Unlike low-level languages, which are close to machine code and hardware operations, high-level languages use natural language elements, symbols, and abstractions that are intuitive for programmers.


    Object-Oriented

    OOP is a programming paradigm that organizes software design around objects—instances of classes. Objects are self-contained units containing data (attributes) and code (methods) that operate on that data. This approach models real-world entities, making programs easier to design, understand, and maintain.

    Concepts

    • Class: A blueprint or template for creating objects, defining attributes and methods.
    • Object: A specific instance of a class with unique attribute values but shared structure.
    • Encapsulation: Keeping an object’s data and methods together while restricting outside access, providing controlled interaction.
    • Inheritance: Allowing a subclass to inherit properties and methods from a superclass, promoting code reuse.
    • Polymorphism: Enabling different objects to respond differently to the same method call, allowing flexible and interchangeable code.
    • Abstraction: Hiding complex implementation details and exposing only necessary parts.

    Advantages

    • Modularity: Programs can be broken into reusable, independent objects.
    • Maintainability: Changes to one object typically do not affect others.
    • Reusability: Code is reused through inheritance and composition.
    • Real-World Modeling: Objects naturally map to real-world entities, making problem-solving intuitive.

    Kernel Mode v.s. User Mode

    The kernel is the core component of an operating system (OS) that manages system resources and facilitates communication between hardware and software. It acts as a bridge between user-level applications and computer hardware, ensuring safe and efficient use of resources like memory, CPU, and input/output devices.

    Kernel-Level Applications (Privileged Mode)

    • Run in kernel mode, also known as privileged mode, with full access to all hardware and system resources.
    • Considered trusted because improper behavior can crash the system or compromise security.
    • Examples: device drivers, memory management routines, core OS functions.

    User-Level Applications (Restricted Mode)

    • Run in user mode, a restricted environment that limits access to hardware and critical resources.
    • Considered less trusted, so the OS restricts their actions to prevent accidental or malicious damage.
    • Examples: web browsers, word processors, games.

    Interaction via System Calls

    • User-level applications cannot directly access hardware or kernel resources. They communicate with the kernel through system calls.
    • A system call is a controlled interface that allows programs to request services like file operations, network communication, or memory allocation.

    Kernel’s Role in Handling Requests

    • The kernel executes requested operations in privileged mode when it receives a system call.
    • After completing the task, the kernel returns control to the user-level application, maintaining system stability and security.

    The kernel is crucial for system stability, security, and efficiency. By separating user mode from kernel mode, operating systems ensure that user applications are restricted while trusted kernel processes manage hardware and resources safely. This separation prevents accidental or malicious misuse of critical system functions and enables multitasking by controlling access to shared resources.

    Example

    Using the standard C library to output Hello World! to the standard output device

    cat # Command used to display the contents of a file
    test.c # The C source file whose contents will be printed to the terminal

    (host) cat test.c

    #include <stdio.h> // Includes the Standard Input/Output library so we can use functions like printf()

    int main(){ // The main function: program execution starts here
      printf(“Hello World!”); // Prints the text “Hello World!” to the standard output (usually the terminal)
      return 0; // Ends the program and returns 0 to the operating system indicating successful execution
    }

    #include <stdio.h>

    int main(){
    printf("Hello World!");
    return 0;
    }

    gcc # GNU C Compiler program used to compile C source code
    test.c # The C source file being compiled
    -o # Option that tells the compiler to name the output file
    test.exe # Name of the compiled executable file that will be created

     (host) gcc test.c -o test.exe

    Output

    Hello World!

    Step by step of the process

    1. User-mode: Program Execution
      • test.exe is loaded into user mode memory.
      • main() function begins execution in user mode.
    2. User-mode: Calling the C Library
      • printf("Hello World!") function is called within main() function.
      • printf() function is part of the C standard library and runs in user mode.
    3. System Call: Switching to Kernel-mode
      • printf internally calls write() system call to send data to stdout.
      • The write() system call is invoked, which causes a context switch from user mode to kernel mode.
    4. Kernel-mode: Writing Output
      • The kernel’s write function is executed with the provided data.
      • The kernel accesses the terminal or console device buffer.
      • The string "Hello World!" is written to the hardware output (e.g., screen).
      • The kernel ensures that the operation is performed safely and that access control is maintained.
    5. Kernel-mode: Return to User-mode
      • After the write operation completes, the kernel returns the result (number of bytes written or error code) back to user mode.
    6. User-mode: Continuing Execution
      • printf() function receives the result from the kernel and completes its execution.
      • The main() function continues executing and returns 0, indicating successful termination.
    7. Program Exit
      • The program exits cleanly, and control is returned to the operating system.

    Some General-Purposes

    Automation and Testing

    Python is widely used for automating repetitive tasks such as file handling, data entry, and system monitoring. It is popular in software testing with frameworks like PyTest and unittest, allowing developers to write automated tests for applications.

    • Example: Automating data extraction from spreadsheets or websites.

    Web Development, Game Development, and Business Applications

    Python powers web development through frameworks like Django and Flask, enabling the creation of scalable and secure web applications. In game development, Python is used with libraries like Pygame to create 2D games and prototypes.

    • Examples: Inventory management, accounting, CRM systems, and desktop software, all benefiting from Python’s rapid development capabilities.

    Data Science, Machine Learning, and Deep Learning

    Python is the primary language for data science, offering libraries such as NumPy, Pandas, Matplotlib, and Seaborn for data analysis and visualization. In machine learning, libraries like scikit-learn, TensorFlow, and PyTorch enable developers to build predictive models and AI applications.

    • Deep learning frameworks in Python are used to create neural networks for tasks like image recognition, natural language processing, and other advanced AI applications.

    Why Python?

    • Easy to learn: Python mimics English; it employs a streamlined syntax focusing on natural language, making learning more straightforward for newcomers.
    • Flexible and reliable: A language for general-purpose programming, it can be used to develop any application with minimum effort.
    • Extremely active community: The community has all sorts of Python professionals that provide access to documentation or answer your questions.

    Python IDLE

    Python’s IDLE is the integrated development environment (IDE) that can be downloaded on different operating systems

    Install Python on macOS

    1. Download the latest Python version from here & Install it
    2. Go to Launchpad and look for IDLE (Integrated Development and Learning Environment)
    3. Or, go to Launchpad, then Others, then Terminal, and finally type python3 there

    Install Python on Windows 64bit

    1. Download the latest Python version from here
    2. When installing it, make sure that you check the “Add Python … to PATH”
    3. Go to Windows Search, then type IDLE (integrated development learning environment)

    Install Python on Linux-Based (Ubuntu)

    1. Go to Terminal, then run sudo apt-get install idle3
    2. Go to Show Applications and look for IDLE
    3. Or, go to Show Applications, look for Terminal, then type IDEL there

    Other options

    Native Apps

    Web Apps