Category: Programming Languages

  • 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
  • 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
  • C Language Compiled Code

    C Language Compiled Code

    C Language Compiled Code refers to the machine-readable version of a program written in the C programming language. When you write C source code in human-readable files (.c and .h), it cannot be executed directly by a computer. A compiler translates this source code through several stages including preprocessing, compilation to assembly, assembling into object code, and linking with libraries to produce a standalone executable file. The resulting compiled code consists of binary instructions that the CPU can interpret and run directly. This makes compiled code fundamentally different from the original C source code, which is intended for humans to read, write, and modify.

    Source Code

    The code is in C language (.c and .h files)

    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;
    }

    Pre-Processor

    This step includes the headers and expand the macros, the generated file have the .i, .ii extensions  

    gcc # GNU C Compiler
    -E # Tells gcc to run only the preprocessor (expands #include, #define, etc.)
    test.c # The C source file being processed
    | # Pipe operator; sends the output of the command on the left to the command on the right
    head # Displays only the first 10 lines of the output

    (host) gcc -E test.c | head

    # 0 "test.c"
    # 0 "<built-in>"
    # 0 "<command-line>"
    # 1 "/usr/include/stdc-predef.h" 1 3 4
    # 0 "<command-line>" 2
    # 1 "test.c"
    # 1 "/usr/include/stdio.h" 1 3 4
    # 28 "/usr/include/stdio.h" 3 4

    Compiler

    The expanded code/preprocessed code gets converted into assembly code, the generated file have the .s, .asm extensions 

    gcc # GNU C Compiler
    -S # Tells gcc to compile the code into assembly language but not create an executable
    test.c # The C source file being compiled

    (host) gcc -S test.c

    cat # Command used to display the contents of a file
    test.s # The generated assembly language file from the compilation step

    (host) cat test.s

            .file   "test.c"
            .text
            .section        .rodata
    .LC0:
            .string "Hello World!"
            .text
            .globl  main
            .type   main, @function
    main:
    .LFB0:
            .cfi_startproc
            pushq   %rbp
            .cfi_def_cfa_offset 16
            .cfi_offset 6, -16
            movq    %rsp, %rbp
            .cfi_def_cfa_register 6
            leaq    .LC0(%rip), %rax
            movq    %rax, %rdi
            movl    $0, %eax
            call    printf@PLT
            movl    $0, %eax
            popq    %rbp
            .cfi_def_cfa 7, 8
            ret
            .cfi_endproc
    .LFE0:
            .size   main, .-main
            .ident  "GCC: (Debian 14.2.0-16) 14.2.0"
            .section        .note.GNU-stack,"",@progbits

    Assembler

    The assembly code gets converted into object code/machine code, the generated file have the .o, .obj extensions  

    gcc # GNU C Compiler
    -c # Compile the source code into an object file (machine code) without linking
    test.c # The C source file being compiled

    (host) gcc -c test.c

    cat # Outputs the contents of the file
    test.o # Object file containing compiled machine code
    | # Pipe operator; sends output of the left command to the right command
    xxd # Converts binary data into a hexadecimal (hex) and ASCII representation
    | # Pipe operator again
    head # Displays only the first 10 lines of the hex output

    (host) cat test.o | xxd | head

    00000000: cffa edfe 0c00 0001 0000 0000 0100 0000  ................
    00000010: 0400 0000 b801 0000 0020 0000 0000 0000  ......... ......
    00000020: 1900 0000 3801 0000 0000 0000 0000 0000  ....8...........
    00000030: 0000 0000 0000 0000 0000 0000 0000 0000  ................
    00000040: 6800 0000 0000 0000 d801 0000 0000 0000  h...............
    00000050: 6800 0000 0000 0000 0700 0000 0700 0000  h...............
    00000060: 0300 0000 0000 0000 5f5f 7465 7874 0000  ........__text..
    00000070: 0000 0000 0000 0000 5f5f 5445 5854 0000  ........__TEXT..
    00000080: 0000 0000 0000 0000 0000 0000 0000 0000  ................
    00000090: 3400 0000 0000 0000 d801 0000 0200 0000  4...............
    ...
    ...
    ...

    Linker

    The last step is combining the object code/machine code and .lib/.a static library files, the generated file have the .exe, elf, bin extensions

    gcc # GNU C Compiler used to compile and link the program
    test.c # The C source file being compiled
    -o # Option to specify the name of the output file
    test.bin # Name of the final executable binary file that will be created

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

    cat # Outputs the contents of the file
    test.bin # The compiled executable binary file
    | # Pipe operator; sends output of one command to another
    xxd # Converts binary data into hexadecimal and ASCII representation
    | # Pipe operator again
    head # Displays the first 10 lines of the output

    (host) cat test.bin | xxd | head

    00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
    00000010: 0300 3e00 0100 0000 5010 0000 0000 0000  ..>.....P.......
    00000020: 4000 0000 0000 0000 9036 0000 0000 0000  @........6......
    00000030: 0000 0000 4000 3800 0e00 4000 1f00 1e00  ....@.8...@.....
    00000040: 0600 0000 0400 0000 4000 0000 0000 0000  ........@.......
    00000050: 4000 0000 0000 0000 4000 0000 0000 0000  @.......@.......
    00000060: 1003 0000 0000 0000 1003 0000 0000 0000  ................
    00000070: 0800 0000 0000 0000 0300 0000 0400 0000  ................
    00000080: 9403 0000 0000 0000 9403 0000 0000 0000  ................
    00000090: 9403 0000 0000 0000 1c00 0000 0000 0000  ...............
    ...
    ...