Author: Giga Alqeeq

  • Microcontrollers

    Microcontrollers

    Microcontroller (MC)

    A microcontroller is a compact, integrated computing device designed to perform specific, dedicated tasks rather than general-purpose computing. Unlike a typical computer, a microcontroller does not run a full operating system; instead, it executes a single program or set of instructions stored in its memory to control or interact with hardware devices. Microcontrollers typically include a processor (CPU), memory (RAM and ROM/flash), and input/output peripherals all on a single chip, enabling direct interface with sensors, actuators, displays, motors, and other electronics.

    Microcontrollers are widely used in embedded systems such as home appliances, automotive electronics, robotics, industrial machines, and IoT devices. They excel in environments where reliability, low power consumption, and real-time control are crucial. This integration enables microcontrollers to operate efficiently and reliably with minimal external components.

    Valued for their low power consumption, cost-effectiveness, compact size, and ability to perform deterministic, real-time operations, microcontrollers form the backbone of countless modern electronic devices and systems.

    Examples

    • Arduino Uno: An open-source micro-controller platform
    • Raspberry Pi Pico: A low-cost, high-performance micro-controller

    Uses

    • A sunrise alarm clock is designed to wake users gradually by simulating the natural light of a sunrise. Instead of using a sudden burst of light, it gradually increases the light intensity to mimic the morning sunlight. This can help regulate circadian rhythms, improve mood, and make waking up more natural and gentle. Some sunrise alarm clocks also offer soothing sounds, such as birdsong or soft music, to complement the light.
    • A weather monitoring system collects, analyzes, and reports various weather data, including temperature, humidity, air pressure, wind speed, and rainfall. These systems can send notifications or alerts about current or forecasted weather conditions. They are used in homes, farms, schools, and research projects to help people make informed decisions about daily activities, agriculture, and safety.

    Arduino Uno Specifications

    • Release: 2010
    • Chip: ATmega328P
    • EEPROM: 1 KB

    Arduino Uno – Front-Side


    General Purpose Input/Output Pins

    GPIO (General Purpose Input/Output) pins are versatile connectors found on microcontrollers, single-board computers such as the Raspberry Pi and Arduino, and other electronic devices. These pins enable the device to interact with the external environment by sending or receiving electrical signals. GPIO pins can be programmed to operate as inputs (to read signals) or outputs (to drive signals), making them highly adaptable for a wide range of applications.

    Digital pins

    Digital pins are input/output (I/O) interfaces on microcontrollers and single-board computers that can be used to read or set specific voltage levels. They operate using binary states, meaning they can recognize or output only two distinct conditions: LOW or HIGH.

    For example, when controlling an LED, setting a digital pin to LOW turns the LED off, while setting it to HIGH turns the LED on. These states correspond to specific voltage levels. Typically, any voltage level above approximately 2.5V is interpreted as HIGH, while anything below this threshold is considered LOW. The exact threshold values may vary depending on the specific microcontroller or board being used.

    In practice, digital pins are not limited to controlling LEDs; they are widely used for tasks such as reading the state of a button (pressed or not), controlling relays, sending signals to sensors, or driving other electronic components. Since digital pins can only represent two states, they are best suited for on/off or true/false conditions, unlike analog pins, which can represent a continuous range of values.

    Analog pins

    Analog pins are input/output (I/O) interfaces on microcontrollers and single-board computers that can read a continuous range of voltage levels, rather than just two discrete states like digital pins. Typically, they can measure voltages between 0V and 5V, though the range may vary depending on the board. This makes analog pins especially useful for applications that require precise or variable input values.

    By connecting a potentiometer (a variable resistor) to an analog pin, the microcontroller can measure different voltage levels based on the knob’s position. Turning the knob changes the resistance, which in turn alters the voltage being read, producing a value that can range from 0 to 5V. This allows the program to interpret a wide spectrum of inputs rather than just “on” or “off.”

    Internally, analog pins use an Analog-to-Digital Converter (ADC) to translate the continuous voltage into a digital value that the processor can understand. For instance, with a 10-bit ADC, the input voltage range (0–5V) is divided into 1024 discrete steps, producing values from 0 to 1023. This enables fine-grained measurement of signals that vary over time, such as light intensity (from a photoresistor), temperature (from a sensor), or sound levels (from a microphone).

    Some analog pins can also be configured for output, but this functionality is limited. Instead of producing a true continuous voltage, they typically use Pulse Width Modulation (PWM) to simulate analog signals. PWM rapidly switches a digital pin between HIGH and LOW states at different duty cycles, creating a variable-voltage effect. This allows controlling devices such as motors, LEDs (for brightness control), or audio output.

    Analog pins are essential whenever your project requires working with gradual changes or input value ranges, offering flexibility that digital pins alone cannot provide. They are ideal for tasks involving sensors and actuators that require precise control and measurement.

  • Microcontroller v.s. Microcomputer

    Microcontroller (MC, UC, μC, or MCU)

    A microcontroller is a compact, integrated computing device designed to perform specific, dedicated tasks rather than general-purpose computing. Unlike a typical computer, a microcontroller does not run a full operating system. Instead, it executes a single program or set of instructions stored in its memory to control or interact with hardware devices. Microcontrollers typically include a processor (CPU), memory (RAM and ROM/flash), and input/output peripherals on a single chip, enabling direct interaction with sensors, actuators, displays, motors, and other electronic components. They are widely used in embedded systems such as home appliances, automotive electronics, robotics, industrial machines, and IoT devices, where reliability, low power consumption, and real-time control are crucial.

    Examples

    Uses

    • Sunrise Alarm Clock: An clock that mimics the natural morning light
    • Weather Monitoring System: A system that monitors weather and sends notification

    Microcomputer (SBC)

    Also known as a system-on-a-chip (SoC) or single-board computer (SBC), this type of computer is a compact, integrated device that combines most of the essential elements of a traditional computer onto a single circuit board or chip. It typically includes a central processing unit (CPU), memory, input/output interfaces, and sometimes specialized components such as graphics processors or networking modules. These computers can perform many tasks and run full operating systems, making them suitable for a wide range of applications. While they are versatile enough for general computing, they are often designed to efficiently process data and support embedded systems, mobile devices, Internet of Things (IoT) applications, and other resource-constrained environments.

    Example

    Uses

    • Desktop: A system that’s designed to be used in one fixed location
    • Web Server: A system that delivers web content
    • Raspberry Pi Oscilloscope: A system that displays and analyzes the waveform of electronic signals
    • Home automation: A system that controls electronic devices in your home
    • Media Server: A system that delivers media content
    • Raspberry Pi Retro Gaming Machine: A system that runs retro games
    • Wi-Fi Repeater: A system that allows you to extend the coverage area of a WiFi network
    • VPN Server: A system that hosts and delivers VPN services

    General Purpose Input/Output Pins (GPIOs)

    GPIO (General Purpose Input/Output) pins are versatile connectors found on microcontrollers, single-board computers like Raspberry Pi and Arduino, and other electronic devices. These pins enable the device to interact with external components by sending or receiving electrical signals. GPIO pins can be programmed to function as inputs (to read signals) or outputs (to send signals), making them essential for a wide range of applications.

    • Digital pins are used to read or set specific voltage levels. For example, an LED can be controlled by setting the digital pin voltage to LOW (off) and HIGH (on). The LOW and HIGH states are determined using a threshold level: voltages above 2.5V are interpreted as HIGH, while voltages below 2.5V are interpreted as LOW.
    • Analog pins are designed to read any voltage between 0V and 5V, allowing precise measurement of values within this range. These pins are particularly useful for reading inputs from a potentiometer, where the value changes with the knob’s position. While analog pins can be used to send signals, their use for sending is more limited than that of digital pins.
  • Python Reading and Writing Files

    Read From File

    To read from the file, you can use the open function to open the file. It opens it and returns a file object that users can use to read or modify the content of that file. The syntax is open(file_name, mode), the file_name is the name of the file you want to interact with, and the mode could be any of these:

    • r read mode
    • w write mode (Overwrites existing file)
    • a append to the end mode
    • b binary mod
      • There are other modes, but these are commonly used

    File Content

    Test1
    Test2

    Example

    temp_file = open(“test_1.txt”, “r”) # Open the file “test_1.txt” in read mode (“r”)
    print(temp_file.read()) # Read the entire contents of the file and print it
    temp_file.close() # Close the file to free system resources

    temp_file = open("test_1.txt","r")

    print(temp_file.read())
    temp_file.close()

    Result

    Test1
    Test2

    Read From File (Line by Line)

    You can use the .readline method to read line by line

    File Content

    Test1
    Test2

    Example

    temp_file = open(“test_1.txt”) # Open the file “test_1.txt” in read mode (default mode is “r”)
    for line in temp_file.readlines(): # Read all lines into a list and iterate through each line
        print(line, end=””) # Print each line without adding extra newlines (end=””)
    temp_file.close() # Close the file to free system resources

    temp_file = open("test_1.txt")
    for line in temp_file.readlines():
    print(line, end="")

    temp_file.close()

    Result

    Test1
    Test2

    Or, you can use the .readlines method

    Example

    temp_file = open(“test_1.txt”) # Open the file “test_1.txt” in read mode (default “r”)
    lines = temp_file.readlines() # Read all lines into a list called ‘lines’
    for line in lines: # Iterate through each line in the list
        print(line, end=””) # Print each line without adding extra newlines
    temp_file.close() # Close the file to free system resources

    temp_file = open("test_1.txt")

    lines = temp_file.readlines()
    for line in lines:
    print(line, end="")

    temp_file.close()

    Write to File

    To write, you can use the .write method

    Example

    temp_file = open(“test_1.txt”, “w”) # Open the file in write mode (“w”); creates the file if it doesn’t exist, or overwrites it if it exists
    temp_file.write(“Test\n”) # Write the string “Test” followed by a newline to the file
    temp_file.close() # Close the file to save changes and free resources
    temp_file = open(“test_1.txt”, “r”) # Reopen the file in read mode (“r”)
    print(temp_file.read()) # Read the entire file contents and print that
    temp_file.close() # Close the file after reading

    temp_file = open("test_1.txt","w")
    temp_file.write("Test\n")
    temp_file.close()

    temp_file = open("test_1.txt","r")
    print(temp_file.read())
    temp_file.close()

    Result

    Test

    Write to File (With User Input)

    You can ask the user for input, then save that to a file

    User Input

    Hello World!

    Example

    temp_file = open(“test_1.txt”, “a+”) # Open the file in append and read mode (“a+”); creates file if it doesn’t exist
    temp_user_input = input(“Enter text: “) # Prompt the user to enter text
    temp_file.write(temp_user_input) # Append the user’s input to the end of the file
    temp_file.close() # Close the file to save changes
    temp_file = open(“test_1.txt”, “r”) # Reopen the file in read mode
    print(temp_file.read()) # Read and print the entire contents of the file
    temp_file.close() # Close the file after reading

    temp_file = open("test_1.txt","a+")
    temp_user_input = input("Enter text: ")
    temp_file.write(temp_user_input)
    temp_file.close()

    temp_file = open("test_1.txt","r")
    print(temp_file.read())
    temp_file.close()

    Result

    Hello World!

    Read\Write Without Close Method

    The .close method is used to close the opened file (It’s a good practice to do that). If you do not want to use that, then use the with the statement, which will automatically close it when flow control leaves the with block

    File Content

    Test1
    Test2

    Example

    with open(“test_1.txt”, “r”) as f: # Open the file “test_1.txt” in read mode; ‘with’ ensures it will be automatically closed
        print(f.read()) # Read the entire file content and print it

    with open("test_1.txt","r") as f:
    print(f.read())

    Result

    Test1
    Test2

    Remove a File

    There are different ways to delete a file, one of them is the use the remove function from the Miscellaneous operating system interfaces module (You need to import it first using import os).

    User Input

    Hello World!

    Example

    import os # Import the os module for interacting with the operating system
    os.remove(“test_1.txt”) # Delete the file “test_1.txt” from the filesystem

    import os
    os.remove("test_1.txt")
  • Python Input

    Input

    The input function is used to get input from the user in string data type (If the user enters [1,2,3], it will be "[1,2,3]" – it becomes a string, not a list)

    Example

    age = input(“Enter your age: “) # Prompt the user to enter their age; the input is returned as a string
    print(“Your age is: “, age) # Print the age entered by the user

    age = input("Enter your age: ")
    print("Your age is: ", age)

    Result

    What is your age? 40
    Your age is: 40

    You can also have that in a loop

    Example

    temp_var = “” # Initialize an empty string variable
    while temp_var != “exit”: # Continue looping until the user types “exit”
        temp_var = input(“Enter text: “) # Prompt the user to enter text
        print(“You entered: “, temp_var) # Print the text entered by the user

    temp_var = ""
    while temp_var != "exit":
    temp_var = input("Enter text: ")
    print("You entered: ", temp_var)

    Result

    Enter text: 10
    You entered: 10
    Enter text: test
    You entered: test
    Enter text: exit
    You entered: exit

    Also, you can check the length

    Example

    temp_var = “” # Initialize an empty string variable
    while len(temp_var) != 4: # Repeat the loop until the user enters a string of length 4
        temp_var = input(“Enter a number: “) # Prompt the user to enter a number
        print(“You entered: “, temp_var) # Print the value entered by the user

    temp_var = ""
    while len(temp_var) != 4:
    temp_var = input("Enter a number: ")
    print("You entered: ", temp_var)

    Result

    Enter a number: a
    You entered: a
    Enter a number: bb
    You entered: bb
    Enter a number: ccc
    You entered: ccc
    Enter a number: dddd
    You entered: dddd

    Input (Type)

    The input function returns a string, and you can check that using the type function

    Example

    temp_var = input(“Enter a number: “) # Prompt the user to enter a number; input is always returned as a string
    print(type(temp_var)) # Print the type of temp_var

    temp_var = input("Enter a number: ")
    print(type(temp_var))

    Result

    Enter a number: 40
    <class 'str'>

    Input (Casting or Converting to int)

    To cast, or convert a string into an int, you can use the int function

    Example

    temp_var = input(“Enter a number: “) # Prompt the user to enter a number; input is returned as a string
    temp_var = int(temp_var) # Convert the input string to an integer
    print(type(temp_var)) # Print the type of temp_var

    temp_var = input("Enter a number: ")
    temp_var = int(temp_var)
    print(type(temp_var))

    Result

    Enter a number: 40
    <class 'int'>

    Input (Safe Casting or Converting)

    Sometimes, functions that evaluate a string into code could be exploited, so it’s recommended that you use safe eval functions such as literal_eval from ast module (If needed)

    Example

    import ast # Import the Abstract Syntax Trees module (used here for safe evaluation)
    temp_var = input(“Enter a float number: “) # Prompt the user to enter a number; input is returned as a string
    temp_var = ast.literal_eval(temp_var) # Safely evaluate the input to its Python type (int, float, etc.)
    print(type(temp_var)) # Print the type of temp_var

    import ast
    temp_var = input("Enter a float number: ")
    temp_var = ast.literal_eval(temp_var)
    print(type(temp_var))

    Result

    Enter a number: 40.0
    <class 'float'>

    Sanitizing Input

    If you are expecting input that does not contain specific characters, you need to sanitize the input (Do not rely on the user to input something without the specific characters)

    Example

    temp_var = input(“Enter a string that does not contain @: “) # Prompt the user to enter a string
    temp_var = temp_var.replace(“@”, “”) # Remove all occurrences of “@” from the string
    print(temp_var) # Print the modified string

    temp_var = input("Enter a string that does not contain @: ")
    temp_var = temp_var.replace("@", "")
    print(temp_var)

    Result

    Enter a number: Hello World!@
    Hello World!
  • Python Pattern Matching With Regular Expressions

    Search for a value

    Some variable data type such as string, list, set and tuple allow you to search them by using the in keyword

    Example

    temp_list = [1, 2, 3] # Create a list with elements 1, 2, 3
    temp_string = “Hello World!” # Create a string variable with value “Hello World!”
    if 1 in temp_list: # Check if the number 1 exists in temp_list
        print(“Found number 1”) # If True, print this message
    if “Hello” in temp_string: # Check if the substring “Hello” exists in temp_string
        print(“Found Hello”) # If True, print this message

    temp_list = [1,2,3]
    temp_string = "Hello World!"

    if 1 in temp_list:
    print("Found number 1")

    if "Hello" in temp_string:
    print("Found Hello")

    Result

    Found number 1
    Found Hello

    Check the length

    You can use the len function to check the length

    Example

    mobile = “1112223333” # Create a string variable representing a mobile number
    if len(mobile) == 10: # Check if the length of the mobile number is exactly 10
        print(“Mobile number length is correct”) # If True, print this message

    mobile = "1112223333"

    if len(mobile) == 10:
    print("Mobile number length is correct")

    Result

    Mobile number length is correct

    Check if Numeric

    You can either use the .isdecimal method or loop the string character and check each one individually

    Example

    mobile = “1112223333” # Create a string variable representing a mobile number
    if len(mobile) == 10: # Check if the mobile number has exactly 10 characters
        print(“Mobile number length is valid”) # If True, print this message
        if mobile.isdecimal(): # Check if all characters in the string are decimal digits (0-9)
            print(“Mobile number pattern is valid”) # If True, print this message

    mobile = "1112223333"

    if len(mobile) == 10:
    print("Mobile number length is valid")
    if mobile.isdecimal():
    print("Mobile number pattern is valid")

    Result

    Mobile number length is valid
    Mobile number pattern is valid

    Or, you can loop each character and check if it’s number or not

    Example

    mobile = “1112223333” # Create a string variable representing a mobile number
    numbers = “1234567890” # String containing all valid numeric digits
    if len(mobile) == 10: # Check if mobile number has exactly 10 characters
        print(“Mobile number length is valid”) # Output message if length is valid
        for character in mobile: # Loop through each character in the mobile number
            if character in numbers: # Check if the character is a valid number
                print(character + ” is valid”) # Print a message for each valid character

    mobile = "1112223333"
    numbers = "1234567890"

    if len(mobile) == 10:
    print("Mobile number length is valid")
    for character in mobile:
    if character in numbers:
    print(character + " is valid")

    Result

    Mobile number length is valid
    1 is valid
    1 is valid
    1 is valid
    2 is valid
    2 is valid
    2 is valid
    3 is valid
    3 is valid
    3 is valid
    3 is valid

    Check by index

    You can also use indexing to check a specific character or sub-string

    Example

    mobile = “111-222-3333” # Create a string variable representing a mobile number in the format XXX-XXX-XXXX
    if len(mobile) == 12: # Check if the total length is 12 characters (including dashes)
        if mobile[3] == “-” and mobile[7] == “-“: # Check if the 4th and 8th characters are dashes
            if mobile[0:3].isdecimal() and mobile[4:7].isdecimal() and mobile[8:12].isdecimal(): # Check if the number parts are all digits: first three, middle three, last four
                print(“Mobile number is valid”) # If all conditions are met, print this message

    mobile = "111-222-3333"

    if len(mobile) == 12:
    if mobile[3] == "-" and mobile[7] == "-":
    if mobile[0:2].isdecimal() and mobile[4:6].isdecimal() and mobile[8:11].isdecimal():
    print("Mobile number is valid")

    Result

    Mobile number is valid

    Regex

    Regex, or regular expression, is a language for finding a particular string based on a search pattern.

    • Characters
      • \d matches 0 to 9
        • \d\d\d\d with 1234567 returns 1234
        • \d+ with 1234567 returns 1234567
      • \w matches word character A to Z, a to z, 0 to 9, and _
        • \w\w with Hello! returns He, and ll
        • \w+ with Hello! returns Hello
      • \s matches white space character
      • . matches any character except line break
        • . with car returns c, a, and r
        • .* with car returns car
    • Character classes
      • [ ] for matching characters within the brackets
        • [abcd] matches a, b, c, or d
        • [a-d] matches a, b, c, or d (The – means to)
        • [^abcd] matches anything except a, b, c, or d (The ^ means negated character class)
        • [^a-d] matches anything except a, b, c, or d (The - means to, and ^ means negated character class)
    • Quantifiers
      • + one or more
        • [1-2] with 112233 returns 1, 1, 2, 2
        • [1-2]+ with 112233 returns 1122
      • * zero or more
        • 1*2* with 112233 returns 1122
      • {2} matches 2 times
        • 1{4} with 111111 returns 1111
    • Boundaries
      • ^ start of string
      • $ end of string
    • Normal
      • 123456 with 123456789 returns 123456
      • abcdef with abcdefghijklmnopqrstuvwxyz returns abcdef
        • Escape special characters using \

    Importing Regex (re) Module

    To use the regex module named re, you need to make it available to use by using the import statement

    Example

    import re # Import Python’s built-in regular expression (regex) module
    print(dir(re)) # Print a list of all attributes, functions, and classes available in the ‘re’ module

    import re
    print(dir(re))

    Result

    ['A', 'ASCII', 'DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'Match', 'Pattern', 'RegexFlag', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_cache', '_compile', '_compile_repl', '_expand', '_locale', '_pickle', '_special_chars_map', '_subx', 'compile', 'copyreg', 'enum', 'error', 'escape', 'findall', 'finditer', 'fullmatch', 'functools', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'template']

    Regex (.search)

    You can use the .search method of re module to find a string based on regex pattern

    Example

    import re # Import the regular expression module
    mobile = “111-222-3333” # Create a string variable representing a mobile number
    if re.search(“\d\d\d-\d\d\d-\d\d\d\d”, mobile): # Search for the pattern XXX-XXX-XXXX using regex
        print(“Mobile number is valid”) # Print this message if the pattern matches

    import re

    mobile = "111-222-3333"

    if re.search("\d\d\d-\d\d\d-\d\d\d\d",mobile):
    print("Mobile number is valid")

    Result

    Mobile number is valid
  • Python Strings

    Indexing

    You can slice a string using smart indexing [] and : or ::

    Example

    temp_string = “abcdefghijk” # Create a string variable with value “abcdefghijk”
    print(temp_string[1:]) # Slice from index 1 to the end and print that
    print(temp_string[2:6]) # Slice from index 2 up to (but not including) index 6 and print that
    print(temp_string[::-1]) # Reverse the string using slicing and print that

    temp_string = "abcdefghijk"

    print(temp_string[1:])
    print(temp_string[2:6])
    print(temp_string[::-1])

    Result

    bcdefghijk
    cdef
    kjihgfedcba

    Concatenation

    You can concatenate strings using the + operator

    Example

    first = “1234” # Create a string variable named first with value “1234”
    second = “5678” # Create a string variable named second with value “5678”
    print(first + second) # Concatenate the two strings and print that

    first = "1234"
    second = "5678"

    print(first + second)

    Result

    12345678

    Replace a letter or sub-string

    You can use the .replace method to replace a word or letter in the string. The .replace method has 3 parameters (old value, new value, count)

    Example

    temp_string = “Hello World!” # Create a string variable with value “Hello World!”
    print(temp_string.replace(“!”, “$”)) # Replace all occurrences of “!” with “$” and print that

    temp_string = "Hello World!"

    print(temp_string.replace("!","$"))

    Result

    Hello World$

    Or, you can replace a word

    Example

    temp_string = “Hello World!” # Create a string variable with value “Hello World!”
    print(temp_string.replace(“World!”, “Mike”)) # Replace the substring “World!” with “Mike” and print that

    temp_string = "Hello World!"

    print(temp_string.replace("World!","Mike"))

    Result

    Hello Mike

    Also, you can remove a word by replacing it with nothing

    Example

    temp_string = “Hello World!” # Create a string variable with value “Hello World!”
    print(temp_string.replace(“World!”, “”)) # Replace the substring “World!” with an empty string and print that

    temp_string = "Hello World!"

    print(temp_string.replace("World!",""))

    Result

    Hello

    Uppercase

    You can use the .upper method to return a copy of the string in upper case

    Example

    temp_string = “Hello World!” # Create a string variable with value “Hello World!”
    print(temp_string.upper()) # Convert all characters in the string to uppercase and print that

    temp_string = "Hello World!"

    print(temp_string.upper())

    Result

    HELLO WORLD!

    Lowercase

    You can use the .lower method to return a copy of the string in upper case

    Example

    temp_string = “Hello World!” # Create a string variable with value “Hello World!”
    print(temp_string.upper()) # Convert all characters in the string to lowercase and print that

    temp_string = "Hello World!"

    print(temp_string.lower())

    Result

    hello world!

    Split

    You can use the .split method to split the string. The split method has 2 parameters (separator, max_split) and the result is a list

    Example

    temp_string = “Hello World!” # Create a string variable with value “Hello World!”
    print(temp_string.split(” “)) # Split the string into a list using space as the separator and print that

    temp_string = "Hello World!"

    print(temp_string.split(" "))

    Result

    ['Hello', 'World!']

    Join

    You can use the .join method to convert a list of strings into one single string

    Example

    temp_items = [“Hello”, “World”, “1”] # Create a list of strings
    print(“,”.join(temp_items)) # Join all elements of the list into a single string, separated by “,” and print that

    temp_items = ["Hello","World","1"]

    print(",".join(temp_items))

    Result

    Hello,World,1

    Find

    You can use .find to return the index of the first occurrence if found; Otherwise, it returns -1

    Example

    temp_string = “0123456789” # Create a string variable with value “0123456789”
    print(temp_string.find(“34”)) # Find the starting index of the substring “34” and print that

    temp_string = "0123456789"

    print(temp_string.find("34"))

    Result

    3

    Count

    You can use .count to return the number of occurrences if found; Otherwise, it returns 0

    Example

    temp_string = “1122334455” # Create a string variable with value “1122334455”
    print(temp_string.count(“1”)) # Count how many times the substring “1” appears in the string and print that

    temp_string = "1122334455"

    print(temp_string.count("1"))

    Result

    2

    String Class

    When you assign a string to a variable, it will create an str object, the str open includes different methods like __str__ that returns the defined string

    Example

    temp_var = “test” # Create a variable named temp_var and assign it the string “test”
    print(type(temp_var)) # Print the type of temp_var

    temp_var = "test"
    print(type(temp_var))

    Result

    <class 'str'>
    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

    Custom Example

    class string(): # Define a class named string
        def __init__(self, var): # Constructor method, called when creating a new object
            self.var = var # Store the argument var in the instance variable self.var
        def __str__(self): # Define the string representation for printing
            return “{} __str__”.format(self.var) # Return the string with “__str__” appended
        def __eq__(self, other): # Define equality comparison for string objects
             if isinstance(other, string): # Check if other is also an instance of string
                return (self.var == other.var) # Compare the stored values
             return False # If other is not a string object, return False
    print(string(“test”) == string(“test”)) # Compare two string objects and print that

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

        def __str__(self):
            return "{} __str__".format(self.var)

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

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

    Result

    True
  • Python Dictionaries

    Dictionary

    A dict is a data type that stores a sequence of key:value pairs (a key is associated with a value). Keys have to be immutable and cannot be duplicated. Notice that dict and set use the same syntax {} . A dict will have key:value pairs, whereas a set, will only have values. Dictionaries are also known as associative arrays or hash tables.

    Example

    dict_1 = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with key-value pairs
    set_1 = {“value_1”, “value_2”} # Create a set with two unique values
    print(type(dict_1), “=”, dict_1) # Print the type of dict_1 and its contents
    print(type(set_1), “=”, set_1) # Print the type of set_1 and its contents

    dict_1 = {"key_1":"value_1","key_2":"value_2"}
    set_1 = {"value_1","value_2"}
    
    print(type(dict_1), "=", dict_1)
    print(type(set_1), "=", set_1)

    Result

    <class 'dict'> = {'key_1': 'value_1', 'key_2': 'value_2'}
    <class 'set'> = {'value_2', 'value_1'}

    Structuring Data

    Dictionaries are very powerful – Let’s say that following is a list of users in a company:

    • Jim drives a Toyota Tacoma 2010, and he is 44 years old
    • Sara drives a Ford F-150 2021, and she is 31 years old

    We can have that organized into a dict

    {
    "Users": {
    "Jim": {
    "car": "Toyota Tacoma 2010",
    "age": 44
    },
    "Sara": {
    "car": "Ford F-150 2021",
    "age": 31
    }
    }
    }

    Or, we can structure that in a list of dictionaries

    [
    {
    "name": "Jim",
    "car": "Toyota Tacoma 2010",
    "age": 44
    },
    {
    "name": "Sara",
    "car": "Ford F-150 2021",
    "age": 31
    }
    ]

    Or, more structured (The more structured, the easier to search or analyze)

    [
    {
    "name": "Jim",
    "car": {
    "model": "Tacoma",
    "make": "Toyota",
    "year": 2010
    },
    "age": 44
    },
    {
    "name": "Sara",
    "car": {
    "model": "F-150",
    "make": "Ford",
    "year": 2021
    },
    "age": 31
    }
    ]

    Accessing Values

    You can access a value by its key. If you have a dict named temp_dict that contains {"key_1":"value_1","key_2":"value_2"}, then you can access the value_1 by using key_1 as temp_dict["key_1"] and so on.

    Example

    temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
    print(temp_dict[“key_1”]) # Access the value associated with the key “key_1” and print it

    temp_dict = {"key_1":"value_1","key_2":"value_2"}
    
    print(temp_dict["key_1"])

    Result

    value_1

    Or you can use the .get method

    Example

    temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
    print(temp_dict[“key_1”]) # Access the value associated with the key “key_1” using the method .get and print it

    temp_dict= {"key_1":"value_1","key_2":"value_2"}
    print(temp_dict.get("key_1"))

    Result

    value_1

    Get All Keys

    To get the keys of a dict, you can use the .keys method

    Example

    temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
    print(temp_dict[“key_1”]) # Print all temp_dict keys

    temp_dict = {"key_1":"value_1","key_2":"value_2"}
    
    print(temp_dict.keys())

    Result

    dict_keys(['key_1', 'key_2'])

    Get All Values

    To get the values of a dict, you can use the .values method

    Example

    temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
    print(temp_dict[“key_1”]) # Print all temp_dict values

    temp_dict = {"key_1":"value_1","key_2":"value_2"}
    print(temp_dict.values())

    Result

    dict_values(['value_1', 'value_2'])

    Add or Update key:value Pair

    You can use the update method to add a new pair or update a current pair. Remember that a dict cannot have duplicate keys. So, if you use an existing key, the value will be updated. Otherwise, a new pair will be added to the dict

    Example

    temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
    temp_dict.update({“key_1”: “new_value”}) # Update the value of “key_1” to “new_value”
    print(temp_dict) # Print the updated dictionary
    temp_dict.update({“key_3”: “value_3”}) # Add a new key-value pair “key_3”: “value_3” to the dictionary
    print(temp_dict) # Print the updated dictionary

    temp_dict = {"key_1":"value_1","key_2":"value_2"}
    
    temp_dict.update({"key_1":"new_value"})print(temp_dict)
    
    temp_dict.update({"key_3":"value_3"})print(temp_dict)

    Result

    {'key_1': 'new_value', 'key_2': 'value_2'}
    {'key_1': 'new_value', 'key_2': 'value_2', 'key_3': 'value_3'}

    Modify a value by its Key

    You can use the assignment statement = with the value corresponding key

    Example

    temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
    temp_dict[“key_1”] = “new_value” # Update the value of “key_1” to “new_value”
    print(temp_dict[“key_1”]) # Access and print the updated value of “key_1”

    temp_dict = {"key_1":"value_1","key_2":"value_2"}

    temp_dict["key_1"] = "new_value"
    print(temp_dict["key_1"])

    Result

    new_value

    Length

    You can use the len function, which will return the number of keys

    Example

    temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
    print(len(temp_dict)) # Print the number of key-value pairs in the dictionary

    temp_dict = {"key_1":"value_1","key_2":"value_2"}
    
    print(len(temp_dict))

    Result

    2

    Delete a key:value Pair

    To delete a key:value pair, use the del function with the key

    Example

    temp_dict = {“key_1”: “value_1”, “key_2”: “value_2”} # Create a dictionary with two key-value pairs
    del(temp_dict[“key_1”]) # Delete the key-value pair with key “key_1” from the dictionary
    print(temp_dict) # Print the updated dictionary

    temp_dict = {"key_1":"value_1","key_2":"value_2"}
    
    del(temp_dict["key_1"])print(temp_dict)

    Result

    {'key_2': 'value_2'}
    new_value

    Pass By Reference

    A dict is an immutable objects are passed by reference to function

    def change_value(param_in): # Define a function that takes one parameter called param_in
        param_in.update({2: “test”}) # Update the dictionary by adding a new key-value pair 2: “test”
    var = {1: “test”} # Create a dictionary with one key-value pair 1: “test”
    print(“Value before passing: “, var) # Print the dictionary before calling the function
    change_value(var) # Call the function; the dictionary is modified inside the function
    print(“Value after passing: “, var) # Print the dictionary after the function call

    Example

    def change_value(param_in):
        param_in.update({2:"test"})

    var = {1:"test"}

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

    Result

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

    List

    A list is a data type that stores multiple\any data types in an ordered sequence. It is mutable and one of the most used data types in Python. You can store integers, floats, strings, and so on.

    Example

    temp_list = [1, 2, 3, 4, 5] # Create a list named temp_list containing the numbers 1 through 5
    print(temp_list) # Print the entire list

    temp_list = [1,2,3,4,5]

    print(temp_list)

    Result

    [1,2,3,4,5]

    The following snippet is a list that uses multiple data types

    Example

    print([1, {1}, (1, 2), “Hello”, 2.9]) # Print a list containing different data types

    print([1,{1},(1,2),"Hello",2.9])

    Result

    [1, {1}, (1, 2), 'Hello', 2.9]

    Indexing

    Indexing means accessing any item inside the list by using its index. If you have a list named listOfstrings that contains ["a","b","c"], then listOfstrings[0] represents the first item. So, listOfstrings[0] is equal to a, listOfstrings[1] is equal to b, and listOfstrings[2] is equal to c.

    Example

    listOfstrings = [“a”, “b”, “c”] # Create a list named listOfstrings containing three letters
    print(listOfstrings[0]) # Print the first element of the list (a)
    print(listOfstrings[1]) # Print the second element of the list (b)
    print(listOfstrings[2]) # Print the third element of the list (c)

    listOfstrings = ["a","b","c"]

    print(listOfstrings[0])
    print(listOfstrings[1])
    print(listOfstrings[2])

    Result

    a
    b
    c

    You can use a smart index to access different elements inside lists, [-1] will return the last item inside the list

    Example

    temp_list = [“a”,”b”,”c”] # Create a list named temp_list containing three letters
    print(temp_list[-1]) # Print the last item

    listOfstrings = ["a","b","c"]

    print(listOfstrings[-1])

    Result

    c

    Or, you can use [-2] will return the second-to-last element of the list

    Example

    temp_list = [“a”,”b”,”c”] # Create a list named temp_list containing three letters
    print(temp_list[-2]) # Print the second-to-last element

    listOfstrings = ["a","b","c"]

    print(listOfstrings[-2])

    Result

    b

    Modify an item inside a list

    You can modify any item inside lists because they are mutable.

    Example

    listOfitems = [“a”, “b”, “c”] # Create a list named listOfitems with three elements
    listOfitems[0] = “aa” # Change the first element from “a” to “aa”
    listOfitems[1] = 2022 # Change the second element from “b” to 2022 (integer)
    print(listOfitems) # Print the updated list

    listOfitems = ["a","b","c"]

    listOfitems[0] = "aa"
    listOfitems[1] = 2022
    print(listOfitems)

    Result

    ['aa', 2022, 'c']

    Duplicates

    A list can have duplicates, whereas a set cannot have duplicates

    Example

    listOfitems = [1, 2, 3] # Create a list named listOfitems with elements 1, 2, 3
    listOfitems[1] = 1 # Change the second element (index 1) from 2 to 1
    listOfitems[2] = 1 # Change the third element (index 2) from 3 to 1
    print(listOfitems) # Print the updated list → Output: [1, 1, 1]

    listOfitems = [1,2,3]

    listOfitems[1] = 1
    listOfitems[2] = 1
    print(listOfitems)

    Result

    [1, 1, 1]

    Loop through a list

    You can loop through a list in a few ways, and you can use the for statement (Remember to indent after the for statement)

    Example

    temp_items = [1, 2, 3] # Create a list named temp_items with elements 1, 2, 3
    for item in temp_items: # Loop through each element in the list
        print(item) # Print the current element (item) in each iteration

    temp_items = [1,2,3]

    for item in temp_items:
    print(item)

    Result

    1
    2
    3

    Or, if you do not want to indent, you can do

    Example

    temp_items = [1, 2, 3] # Create a list named temp_items with elements 1, 2, 3
    for item in temp_items:print(item): # Loop through each element in the list, print the current element (item) in each iteration

    temp_items = [1,2,3]

    for item in temp_items:print(item)

    Result

    1
    2
    3

    Length

    To get the length of a list, you can use the len function, or you can look through the items and increase a counter value

    Example

    temp_items = [1, 2, 3] # Create a list named temp_items with elements 1, 2, 3
    print(len(temp_items)) # Print the size of the list

    temp_items = [1,2,3]

    print(len(temp_items))

    Result

    3

    Add item

    To add an item to a list, you can use .append method

    temp_items = [1, 2, 3] # Create a list named temp_items with elements 1, 2, 3
    temp_items.append(4) # Add the element 4 to the end of the list using append()
    print(temp_items) # Print the updated list

    Example

    temp_items = [1,2,3]

    temp_items.append(4)
    print(temp_items)

    Result

    [1, 2, 3, 4]

    Remove item by Value

    To remove an item inside a list, you can use .remove method. This method will remove an item by value

    Example

    temp_items = [1, 2, 3] # Create a list named temp_items with elements 1, 2, 3
    temp_items.remove(2) # Remove number 2 from the list
    print(temp_items) # Print the updated list

    temp_items = [1,2,3]

    temp_items.remove(2)
    print(temp_items)

    Result

    [1, 3]

    Remove item by Index

    To remove an item inside a list, you can use del statement. This statement will remove an item by index, but you will need to use [index]

    Example

    temp_items = [1, 2, 3] # Create a list named temp_items with elements 1, 2, 3
    del temp_items[1] # Remove number 2 from the list by index
    print(temp_items) # Print the updated list

    temp_items = [1,2,3]

    del temp_items[1]
    print(temp_items)

    Result

    [1, 3]

    Clear a list

    To remove all items from a list, you can use the .clear method

    Example

    temp_items = [1, 2, 3] # Create a list named temp_items with elements 1, 2, 3
    temp_items.clear() # Clear all the items from the list
    print(temp_items) # Print the updated list

    temp_items = [1,2,3]

    temp_items.clear()
    print(temp_items)

    Result

    []

    Pass By Reference

    List is an 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; the list is modified inside the function
    print(“Value after passing: “, var) # Print the list after the 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)

    Result

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

    Function Structure

    Function is a reusable block of code that has 2 parts:

    1. A def statement that defines the function name – E.g. def example_1(): or def example(param_in):
    2. Function body that contains a block of code that will be executed when the function is called

    The following snippet will declare a function, but it won’t execute it:

    Example

    def example_1(): # Define a function named example_1
        temp_val = 10 # Create a local variable temp_val and assign it the value 10
        print(temp_val) # Print the value of temp_val when the function is called

    def example_1():
    temp_val = 10
    print(temp_val)

    Result

     

    If you want to execute\call it, use example_1() somewhere else without def statement:

    Example

    def example_1(): # Define a function named example_1
        temp_val = 10 # Create a local variable temp_val and assign it the value 10
        print(temp_val) # Print the value of temp_val when the function is called

    example_1(): # Call the function to execute its code

    def example_1():
    temp_val = 10
    print(temp_val)

    example_1()

    Result

    10

    Function

    You can define a function using the def statement, followed by the function’s name, then (): and the rest have to be indented (spaces or tabs). To call the function, use the function name + ().

    Example

    def temp_function(): # Define a function named temp_function that takes no parameters
        print(“What’s up”) # Print the message “What’s up” when the function is called

    temp_function() # Call the function to execute its code

    def temp_function():
    print("What's up")

    temp_function()

    Result

    What's up

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

    Example

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

    temp_function(“What’s up”) # Call the function and pass the string “What’s up” as an argument

    def temp_function(param):
    print(param)

    temp_function("What's up")

    Result

    What's up

    Functions Arguments & Parameters

    To pass arguments to a function E.g. Tim, declare a function and add parameters inside the parentheses what_is_your_name(first_param):

    Example

    def what_is_your_name(first_param): # Define a function that takes one parameter called first_param
        print(“You passed”, first_param) # Print the message along with the value passed to the function

    what_is_your_name(“Tim”) # Call the function with a string
    what_is_your_name(1) # Call the function with an integer
    what_is_your_name([“Nancy”, 2]) # Call the function with a list containing a string and an integer

    def what_is_your_name(first_param):
        print("You passed", first_param)
    
    what_is_your_name("Tim")
    what_is_your_name(1)
    what_is_your_name(["Nancy",2])

    Result

    You passed Tim
    You passed 1
    You passed ['Nancy', 2]

    Multiple Arguments & Parameters

    You can pass multiple arguments to a function if a function is declared with multiple parameters. You cannot declare a function with duplicate parameters; they must be unique. E.g. you declared def sayFirstLast(first, last): that has first and last as parameters and prints(first, last) in the body.

    Example

    def sayFirstLast(first, last): # Define a function with two parameters: first and last
        print(first, last) # Print the values of first and last separated by a space

    sayFirstLast(“Dennis”,”Smith”) # Call the function with first=”Dennis” and last=”Smith”
    sayFirstLast(“Sara”,”Mars”) # Call the function with first=”Sara” and last=”Mars”

    def sayFirstLast(first, last):
    print(first, last)

    sayFirstLast("Dennis","Smith")
    sayFirstLast("Sara","Mars")

    Result

    Dennis Smith
    Sara Mars

    Re-declaring Functions

    You can declare or re-declare a function using the same def statement. If you have a function named say_hello() that prints Hello, you can re-declare again and change Hello to Hi (Because Python executes code line by line)

    Example

    def say_hello(): # Define a function named say_hello
        print(“Hello”) # Print “Hello” when the function is called

    say_hello() # Call the first version of say_hello

    def say_hello(): # Redefine the function say_hello (overwrites the previous one)
        print(“Hi”) # Print “Hi” when the new function is called

    say_hello() # Call the new version of say_hello 

    def say_hello():
        print("Hello")
    
    say_hello()
    def say_hello():
        print("Hi")
    
    say_hello()

    Result

    Hello
    Hi

    Function Return

    If you want to return a value from a function, use the return statement. Let’s say that you have a function named multiply_by_4 that multiplies any number you pass to it (It does not output the number); you can get the result using the return statement.

    Example

    def say_hello(param_1): # Define a function that takes one parameter called param_1
        return param_1 * 4 # Return the value of param_1 multiplied by 4

    returned_value = say_hello(10) # Call the function with 10; the result (10*4=40) is stored in returned_value
    print(returned_value) # Print the value stored in returned_value → Output: 40
    print(say_hello(100)) # Call the function with 100; returns 100*4=400
    print(say_hello(say_hello(1))) # Nested call: Inner say_hello(1) returns 1*4 = 4, outer say_hello(4) returns 4*4 = 16

    def say_hello(param_1):
        return param_1 * 4
    
    returned_value = say_hello(10)print(returned_value)
    print(say_hello(100))
    print(say_hello(say_hello(1)))

    Result

    40
    400
    16

    Empty Function

    A function with an empty block will cause an error. E.g. IndentationError: expected an indented block. To write an empty function, you can use the pass statement in the body.

    def empty_function(): # Define a function named empty_function that does nothing
        pass # pass is a placeholder; it allows the function to exist without any action

    empty_function() # Call the function; nothing happens because it contains only pass

    Example

    def empty_function():
        pass
    
    empty_function()

    Result


    Function Overloading

    You can use the function overloading technique to define multiple functions with the same name but taking different arguments

    Example

    from functools import singledispatch # Import singledispatch to create a function that behaves differently based on input type

    @singledispatch
    def temp_function(param_in): # Define the generic function for types that don’t have a specific handler
        print(“Other:”, param_in) # Default behavior for unregistered types

    @temp_function.register(int) # Register a special behavior for int type
    def _(param_in):                      
        print(“Integer:”, param_in) # Print “Integer:” followed by the value if param_in is an int

    @temp_function.register(str) # Register a special behavior for str type
    def _(param_in):
        print(“String:”, param_in) # Print “String:” followed by the value if param_in is a string

    temp_function(1) # Call with an int
    temp_function(“Test”) # Call with a string
    temp_function({1,2,3}) # Call with a set

    from functools import singledispatch

    @singledispatch
    def temp_function(param_in):
        print("Other:", param_in)

    @temp_function.register(int)
    def _(param_in):
        print("Integer:", param_in)

    @temp_function.register(str)
    def _(param_in):
        print("String:", param_in)

    temp_function(1)
    temp_function("Test")
    temp_function({1,2,3})

    Output

    Integer: 1
    String: Test
    Other: {1, 2, 3}

  • 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