Basic Coding Topics for Online Tests

Python Basics

Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.

Key Concepts:

Syntax

Python syntax is known for its readability and simplicity. Key aspects include:

  • Indentation: Python uses indentation to define code blocks, unlike other languages that use curly braces. This enforces clean, readable code.
  • Comments: Comments are added using the # symbol. They are used to explain code and are ignored during execution.
  • Basic Structure: A simple Python program typically starts with function definitions and ends with script execution.
# This is a comment
        def hello_world():
            print("Hello, World!")
        hello_world()
        

Data Types

Python supports several data types:

  • Integers: Whole numbers, e.g., 5, -3
  • Floats: Decimal numbers, e.g., 3.14, -0.001
  • Strings: Textual data, e.g., "Hello", 'World'
  • Lists: Ordered collections of items, e.g., [1, 2, 3], ['a', 'b', 'c']
  • Tuples: Immutable ordered collections, e.g., (1, 2, 3), ('a', 'b', 'c')
  • Dictionaries: Collections of key-value pairs, e.g., {'key1': 'value1', 'key2': 'value2'}
number = 10          # Integer
        price = 19.99         # Float
        name = "Alice"        # String
        numbers = [1, 2, 3]  # List
        coordinates = (10, 20) # Tuple
        person = {'name': 'Alice', 'age': 25} # Dictionary
        

Operators

Python includes various operators for performing arithmetic, comparison, and logical operations.

  • Arithmetic Operators: +, -, *, /, %, ** (exponentiation), // (floor division)
  • Comparison Operators: ==, !=, >, <, >=, <=
  • Logical Operators: and, or, not
# Arithmetic Operators
        a = 10
        b = 3
        print(a + b)  # Output: 13
        print(a - b)  # Output: 7
        print(a * b)  # Output: 30
        print(a / b)  # Output: 3.3333
        print(a % b)  # Output: 1
        
        # Comparison Operators
        print(a == b) # Output: False
        print(a > b) # Output: True
        
        # Logical Operators
        print(a > 5 and b < 5) # Output: True
        print(not (a > 5))    # Output: False
        

Conditions

Conditional statements control the flow of execution based on certain conditions.

  • if: Executes a block of code if the condition is true.
  • elif: Checks another condition if the previous ones are false.
  • else: Executes a block of code if none of the previous conditions are true.
score = 85
        if score >= 90:
            grade = 'A'
        elif score >= 80:
            grade = 'B'
        else:
            grade = 'C'
        
        print(f"Grade: {grade}")  # Output: Grade: B
        

Loops

Loops allow you to execute a block of code multiple times.

  • for Loop: Iterates over a sequence (like a list or range).
  • while Loop: Continues execution as long as a condition is true.
# for Loop
        for i in range(3):
            print(i)  # Output: 0 1 2
        
        # while Loop
        count = 0
        while count < 3:
            print(count)  # Output: 0 1 2
            count += 1
        

Strings

Strings are sequences of characters and can be manipulated in various ways.

  • Concatenation: Joining strings using the + operator.
  • Repetition: Repeating strings using the * operator.
  • Slicing: Extracting substrings using index notation.
  • Methods: Built-in methods like upper(), lower(), and replace().
text = "Hello, World!"
        print(text + " Welcome!")  # Output: Hello, World! Welcome!
        print(text * 2)            # Output: Hello, World!Hello, World!
        print(text[0:5])           # Output: Hello
        print(text.upper())       # Output: HELLO, WORLD!
        

Control Structures

Control structures in Python allow for conditional execution and looping through code blocks.

  • Conditional Statements: Used for decision-making with if, elif, and else.
  • Loops: Used for iteration with for and while.
# Conditional Statement
        age = 20
        if age >= 18:
            print("Adult")
        else:
            print("Minor")
        
        # Loop Example
        for i in range(5):
            print(i)  # Output: 0 1 2 3 4
        

Functions

Functions in Python are defined using the def keyword. They can take arguments and return values.

  • Definition: Functions are defined using def, followed by the function name and parentheses.
  • Arguments: Functions can accept parameters.
  • Return Values: Functions return values using the return keyword.
def greet(name):
            return f"Hello, {name}!"
        
        print(greet("Alice"))  # Output: Hello, Alice!
        

HTML Basics

HTML (HyperText Markup Language) is the standard language used to create and design web pages. It provides the basic structure for web documents by defining elements like headings, paragraphs, links, images, and other content. HTML uses tags to structure content and attributes to provide additional information about elements.

Key Concepts:

HTML Document Structure

The structure of an HTML document is organized into a series of nested elements. The fundamental tags include:

  • <html>: The root element that contains all other HTML elements.
  • <head>: Contains meta-information about the document, such as the title and links to stylesheets. It does not display content directly on the page.
  • <body>: Contains the content of the document that is displayed on the web page, including headings, paragraphs, images, and other elements.
<!DOCTYPE html>
        <html>
            <head>
                <title>Page Title</title>
                <link rel="stylesheet" href="styles.css">
            </head>
            <body>
                <h1>Welcome to My Website</h1>
                <p>This is a paragraph.</p>
                <img src="image.jpg" alt="Description">
            </body>
        </html>
        

Common Elements

HTML includes a variety of elements to structure content on a web page:

  • <h1> to <h6>: Headings that define the importance of sections. <h1> is the largest and most important, while <h6> is the smallest.
  • <p>: Defines a paragraph of text.
  • <a>: Defines a hyperlink that links to another page or resource. Uses the `href` attribute to specify the URL.
  • <img>: Embeds an image in the document. Uses `src` attribute to specify the image URL and `alt` attribute for alternative text.
  • <ul>: Defines an unordered (bulleted) list.
  • <ol>: Defines an ordered (numbered) list.
  • <li>: Defines a list item in both unordered and ordered lists.
<h1>Main Heading</h1>
        <p>This is a paragraph with a link to an external website.</p>
        <img src="logo.png" alt="Company Logo">
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
        </ul>
        <ol>
            <li>First</li>
            <li>Second</li>
        </ol>
        

Attributes

Attributes provide additional information about HTML elements and modify their behavior or appearance. They are included in the opening tag of an element.

<img id="logo" class="responsive" src="logo.png" alt="Company Logo">
        <a href="https://www.example.com" class="external-link">Visit Example</a>
        

JavaScript Basics

JavaScript is a programming language that enables interactive web pages. It is a core technology of the World Wide Web, alongside HTML and CSS, and is used to enhance user interaction and control web page behavior. JavaScript can manipulate the DOM (Document Object Model), handle events, and perform various other tasks to make web pages dynamic and interactive.

Key Concepts:

Variables

Variables are containers for storing data values. In JavaScript, you can declare variables using `var`, `let`, and `const`:

  • var: The oldest keyword for declaring variables. It is function-scoped and can be re-declared and updated.
  • let: Introduced in ES6 (ECMAScript 2015), it is block-scoped and can be updated but not re-declared in the same scope.
  • const: Also introduced in ES6, it is block-scoped and cannot be updated or re-declared. It is used for variables whose values should remain constant.

        let name = 'John'; // Block-scoped variable
        const age = 30; // Block-scoped constant
        var isStudent = true; // Function-scoped variable
        
        console.log(name); // Output: John
        console.log(age); // Output: 30
        console.log(isStudent); // Output: true
        

Data Types

JavaScript supports several data types:

  • String: Represents a sequence of characters. Enclosed in single quotes (`'`), double quotes (`"`), or backticks (`` ` ``).
  • Number: Represents numeric values, including integers and floating-point numbers.
  • Boolean: Represents a true or false value.
  • Array: An ordered collection of values. Arrays can contain elements of different types.
  • Object: A collection of key-value pairs. Objects are used to store and manage data.

        let name = 'Alice'; // String
        let age = 25; // Number
        let isStudent = false; // Boolean
        
        // Array
        let fruits = ['Apple', 'Banana', 'Cherry'];
        
        // Object
        let person = {
            firstName: 'John',
            lastName: 'Doe',
            age: 30
        };
        
        console.log(fruits[0]); // Output: Apple
        console.log(person.firstName); // Output: John
        

Functions

Functions are blocks of code designed to perform a specific task. They can be declared and called, and can accept parameters and return values:

  • Function Declaration: A function can be declared using the `function` keyword.
  • Function Invocation: A function is called by using its name followed by parentheses.
  • Parameters: Functions can accept parameters to process input values.
  • Return Values: Functions can return values using the `return` keyword.

        function greet(name) {
            return `Hello, ${name}!`;
        }
        
        let message = greet('Alice');
        console.log(message); // Output: Hello, Alice!
        

Events

Events are actions or occurrences that happen in the browser, such as clicks, form submissions, or key presses. JavaScript can be used to handle these events and execute code in response:

  • addEventListener: Attaches an event handler to an element. It allows you to specify the type of event and the function to be executed.
  • Event Object: Provides information about the event, such as the type of event and the target element.

        document.querySelector('button').addEventListener('click', function(event) {
            alert('Button was clicked!');
            console.log(event); // Output: Event object with details about the click event
        });
        

Data Types

Data types define the kind of data that can be stored and manipulated within a programming language. Understanding data types is fundamental to writing effective and error-free code. In JavaScript, data types are categorized into primitive and composite types, and you can perform type conversion between these types.

Key Concepts:

Primitive Data Types

Primitive data types are the basic types of data in JavaScript. They represent single values and are immutable (cannot be changed).

  • Number: Represents numeric values, including integers and floating-point numbers. JavaScript does not differentiate between integer and floating-point numbers; all numbers are of type `Number`.
  • String: Represents a sequence of characters enclosed in single quotes (`'`), double quotes (`"`), or backticks (`` ` ``). Strings are immutable.
  • Boolean: Represents a logical entity with two possible values: `true` or `false`.
  • Null: Represents a deliberate non-value. It is used to indicate that a variable has no value or is empty.
  • Undefined: Represents a variable that has been declared but has not been assigned a value. It is the default value for uninitialized variables.

        let age = 25; // Number
        let name = 'Alice'; // String
        let isStudent = true; // Boolean
        let emptyValue = null; // Null
        let notAssigned; // Undefined
        
        console.log(typeof age); // Output: number
        console.log(typeof name); // Output: string
        console.log(typeof isStudent); // Output: boolean
        console.log(typeof emptyValue); // Output: object
        console.log(typeof notAssigned); // Output: undefined
        

Composite Data Types

Composite data types are structures that can hold multiple values. They are mutable, meaning their contents can be modified.

  • Array: An ordered collection of values, which can be of any data type. Arrays are indexed, meaning each value has a numeric index starting from 0.
  • Object: A collection of key-value pairs where keys are strings (or Symbols) and values can be any data type. Objects are useful for grouping related data together.

        let fruits = ['Apple', 'Banana', 'Cherry']; // Array
        let person = {
            firstName: 'John',
            lastName: 'Doe',
            age: 30
        }; // Object
        
        console.log(fruits[1]); // Output: Banana
        console.log(person.firstName); // Output: John
        

Type Conversion

Type conversion refers to the process of converting one data type to another. In JavaScript, type conversion can be implicit (automatic) or explicit (manual).

  • Implicit Conversion: JavaScript automatically converts data types as needed. For example, when adding a number to a string, JavaScript converts the number to a string.
  • Explicit Conversion: You can manually convert between data types using built-in functions and methods.

        let num = 5;
        let str = '10';
        
        // Implicit Conversion
        let result = num + str; // '510' (number is converted to string)
        console.log(result);
        
        // Explicit Conversion
        let numberFromStr = Number(str); // Converts string to number
        console.log(numberFromStr + num); // Output: 15
        
        let booleanValue = Boolean(0); // Converts 0 to boolean (false)
        console.log(booleanValue); // Output: false
        

Control Flows in Programming

Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a programming language. Understanding control flow is essential for writing effective and efficient code.

Key Concepts:

Conditional Statements

Conditional statements allow you to execute certain blocks of code based on specific conditions. They are fundamental to decision-making in programming.

  • if Statement: Executes a block of code if the condition is true.
  • else Statement: Executes a block of code if the condition in the `if` statement is false.
  • else if (or elif in Python) Statement: Checks additional conditions if the previous conditions are false.
  • switch Statement: (Not in Python) Allows multiple possible execution paths based on the value of a variable.
# Python Example
        age = 20
        if age >= 18:
            print("You are an adult.")
        else:
            print("You are a minor.")
        
        # JavaScript Example
        let day = "Monday";
        switch (day) {
            case "Monday":
                console.log("Start of the work week.");
                break;
            case "Friday":
                console.log("End of the work week.");
                break;
            default:
                console.log("It's a regular day.");
        }
        

Loops

Loops allow you to execute a block of code multiple times, which is useful for tasks that require repeated actions.

  • for Loop: Iterates over a sequence (like a list, range, or string) and executes a block of code for each item.
  • while Loop: Repeats a block of code as long as a specified condition is true.
  • do-while Loop: (Not in Python) Similar to `while`, but ensures the block of code is executed at least once before checking the condition.
# Python Example
        # for Loop
        for i in range(5):
            print(i)  # Output: 0 1 2 3 4
        
        # while Loop
        count = 0
        while count < 5:
            print(count)  # Output: 0 1 2 3 4
            count += 1
        
        # JavaScript Example
        let i = 0;
        do {
            console.log(i); // Output: 0 1 2 3 4
            i++;
        } while (i < 5);
        

Exception Handling

Exception handling allows you to manage errors and exceptional conditions that may occur during the execution of your program. It ensures that your program can handle errors gracefully without crashing.

  • try Block: Contains code that may potentially cause an error.
  • catch Block: (or except in Python) Catches and handles the exception if an error occurs in the `try` block.
  • finally Block: Contains code that will always execute, regardless of whether an exception was raised or not. It is often used for cleanup actions.
# Python Example
        try:
            result = 10 / 0  # This will raise a ZeroDivisionError
        except ZeroDivisionError:
            print("Cannot divide by zero!")
        finally:
            print("Execution completed.")
        
        # JavaScript Example
        try {
            let result = 10 / 0; // This will not raise an error in JavaScript
        } catch (error) {
            console.log("An error occurred:", error);
        } finally {
            console.log("Execution completed.");
        }