EASYTUTORGUIDE

Practical tutorials, tools, courses, digital skills, and business promotion.

Free Learning

JavaScript – Chapter 2: Development Environment

Learn what JavaScript is, where it runs, why it is important, and how beginners can start using it with simple examples and clear output.

Beginner Friendly JavaScript Basics Web Development Code Examples
JavaScript Lesson 2 Chapter 2 Topics Day / Night Mode

Main reading content

  • Ch 4 Chapter 4Python Data Types
  • 4.1 Understanding Data Types

    A data type tells Python what kind of value is being stored and what operations are allowed with that value. For example, a number can be added, while text can be joined with other text. Understanding data types helps beginners avoid mistakes and choose the correct kind of value for each task.

    Example: Check different data types

    # Store a whole number.
    age = 25
    
    # Store text.
    name = "Sara"
    
    # Store a true or false value.
    is_student = True
    
    # Display each value and its type.
    print(age, type(age))
    print(name, type(name))
    print(is_student, type(is_student))
    Output:
    25 <class 'int'>
    Sara <class 'str'>
    True <class 'bool'>

    Explanation: Python identifies 25 as an integer, "Sara" as a string, and True as a Boolean value. The type() function shows the exact data type of each variable.

    4.2 Numeric Types

    Python has three main numeric types: integers, floating-point numbers, and complex numbers. Integers are whole numbers, floats include decimal points, and complex numbers contain a real and imaginary part. Beginners use numbers for prices, ages, measurements, scores, calculations, and many other common programming tasks.

    Example: Use the three numeric types

    # Integer: a whole number.
    items = 4
    
    # Float: a decimal number.
    price = 3.50
    
    # Complex number.
    signal = 2 + 3j
    
    print(type(items))
    print(type(price))
    print(type(signal))
    Output:
    <class 'int'>
    <class 'float'>
    <class 'complex'>

    Explanation: The first value is an integer because it has no decimal point. The second is a float because it contains a decimal. The third is complex because it uses j for the imaginary part.

    4.3 Integers

    An integer is a whole number without a decimal point. Integers may be positive, negative, or zero. They are commonly used for ages, quantities, scores, years, and counting. Python integers can be very large, so beginners usually do not need to worry about a small fixed maximum size.

    Example: Work with integers

    # Store whole numbers.
    students = 30
    absent = 4
    
    # Subtract to find how many are present.
    present = students - absent
    
    print("Students present:", present)
    Output:
    Students present: 26

    Explanation: Both students and absent are integers. Python subtracts 4 from 30 and stores the result, 26, in the present variable.

    4.4 Floating-Point Numbers

    A floating-point number, usually called a float, is a number that includes a decimal point. Floats are useful for prices, temperatures, distances, percentages, and measurements. Beginners should remember that some decimal calculations may show tiny rounding differences because computers store floating-point values in a special binary format.

    Example: Calculate a total price

    # Store a decimal price.
    price = 4.75
    
    # Store the quantity.
    quantity = 3
    
    # Multiply the price by the quantity.
    total = price * quantity
    
    print("Total:", total)
    Output:
    Total: 14.25

    Explanation: The price is a float because it contains a decimal point. Python multiplies 4.75 by 3 and produces the floating-point result 14.25.

    4.5 Complex Numbers

    A complex number contains two parts: a real part and an imaginary part. Python writes the imaginary part using the letter j. Complex numbers are not used in most beginner programs, but they are important in engineering, electronics, physics, signal processing, and advanced mathematics. Python supports them directly.

    Example: Read parts of a complex number

    # Create a complex number.
    value = 5 + 2j
    
    # Display the complete number.
    print("Complex number:", value)
    
    # Display its two parts.
    print("Real part:", value.real)
    print("Imaginary part:", value.imag)
    Output:
    Complex number: (5+2j)
    Real part: 5.0
    Imaginary part: 2.0

    Explanation: The number contains a real part of 5 and an imaginary part of 2. Python provides the .real and .imag attributes to read these parts separately.

    4.6 Strings

    A string is a sequence of text characters placed inside quotation marks. Strings can contain names, sentences, symbols, numbers used as text, and even empty text. Beginners use strings to display messages, store user names, create labels, and work with written information. Strings may use single or double quotation marks.

    Example: Join two strings

    # Store first and last names as strings.
    first_name = "Amina"
    last_name = "Khan"
    
    # Join the strings with a space.
    full_name = first_name + " " + last_name
    
    print(full_name)
    Output:
    Amina Khan

    Explanation: The plus sign joins the two strings. The extra string containing one space keeps the first and last names separated in the final output.

    4.7 Boolean Values

    A Boolean value can be only True or False. Booleans are useful when a program needs to make decisions, such as checking whether a password is correct, whether a user is old enough, or whether an item is available. Python writes Boolean values with a capital first letter.

    Example: Compare a student's score

    # Store the student's score.
    score = 78
    
    # Check whether the score is at least 50.
    passed = score >= 50
    
    print("Passed:", passed)
    Output:
    Passed: True

    Explanation: Python checks whether 78 is greater than or equal to 50. Because the comparison is correct, the result is the Boolean value True.

    4.8 Lists

    A list stores several values in one variable. List items are written inside square brackets and separated by commas. Lists keep their order and can be changed after creation. Beginners often use lists for names, products, scores, tasks, or any collection where items may be added, removed, or updated.

    Example: Add an item to a list

    # Create a list of fruits.
    fruits = ["apple", "banana", "orange"]
    
    # Add another fruit.
    fruits.append("mango")
    
    print(fruits)
    Output:
    ['apple', 'banana', 'orange', 'mango']

    Explanation: The list starts with three fruits. The append() method adds "mango" to the end, so the updated list contains four items.

    4.9 Tuples

    A tuple is an ordered collection similar to a list, but its items cannot be changed after the tuple is created. Tuples use parentheses instead of square brackets. They are useful for values that should stay fixed, such as coordinates, calendar dates, color codes, or settings that should not be modified accidentally.

    Example: Store a fixed coordinate

    # Store x and y coordinates in a tuple.
    position = (10, 25)
    
    # Read each item by its index.
    print("X:", position[0])
    print("Y:", position[1])
    Output:
    X: 10
    Y: 25

    Explanation: The tuple stores two fixed values. Index 0 gives the first value, and index 1 gives the second value. The tuple keeps the original order.

    4.10 Sets

    A set stores unique values, which means duplicate items are automatically removed. Sets use curly braces and do not guarantee a fixed display order. They are useful when beginners need to remove duplicates, check membership quickly, or compare groups of items. Set items themselves must be immutable values.

    Example: Remove duplicate values

    # Create a set with repeated values.
    numbers = {1, 2, 2, 3, 3, 3}
    
    # Display the set.
    print(numbers)
    Output:
    {1, 2, 3}

    Explanation: The repeated 2 and 3 values appear only once because sets keep unique items. The order shown by a set may be different on another run or system.

    4.11 Frozen Sets

    A frozen set is an unchangeable version of a set. It stores unique items, but values cannot be added or removed after creation. Frozen sets are useful when a collection must stay fixed or when a set needs to be used as a dictionary key. Beginners create one with the frozenset() function.

    Example: Create a frozen set

    # Create a frozen set from a list.
    permissions = frozenset(["read", "write", "read"])
    
    print(permissions)
    print("read" in permissions)
    Output:
    frozenset({'read', 'write'})
    True

    Explanation: The duplicate "read" value is removed. The membership check returns True because "read" is stored in the frozen set.

    4.12 Dictionaries

    A dictionary stores information as key-value pairs. Each key acts like a label that points to a value. Dictionaries use curly braces, with a colon between each key and value. They are useful for student records, product information, settings, contact details, and other structured data that needs meaningful labels.

    Example: Read values from a dictionary

    # Create a dictionary for one student.
    student = {
        "name": "Omar",
        "age": 14,
        "grade": 8
    }
    
    print(student["name"])
    print(student["grade"])
    Output:
    Omar
    8

    Explanation: The keys "name" and "grade" are used to retrieve their matching values. This is easier to understand than remembering numbered positions.

    4.13 Ranges

    A range represents a sequence of numbers and is commonly used with loops. The range() function can accept a start value, stop value, and step value. The stop number is not included. Ranges are memory-efficient because Python does not need to store every number as a separate list item.

    Example: Create numbers from 1 to 5

    # Create a range starting at 1 and stopping before 6.
    numbers = range(1, 6)
    
    # Convert the range to a list for display.
    print(list(numbers))
    Output:
    [1, 2, 3, 4, 5]

    Explanation: The range begins at 1 and stops before 6, so it produces 1 through 5. Converting it to a list makes all numbers visible at once.

    4.14 Bytes

    The bytes type stores binary data as a fixed sequence of numbers from 0 to 255. It is often used for files, images, network messages, and encoded text. Bytes are immutable, so their contents cannot be changed after creation. Beginners usually see bytes when reading files or encoding strings.

    Example: Convert text to bytes

    # Store normal text.
    message = "Hi"
    
    # Encode the string as UTF-8 bytes.
    data = message.encode("utf-8")
    
    print(data)
    print(type(data))
    Output:
    b'Hi'
    <class 'bytes'>

    Explanation: The encode() method converts the string into bytes. The letter b before the quotes shows that the value is binary bytes instead of a normal string.

    4.15 Byte Arrays

    A byte array is similar to bytes, but it can be changed after creation. It stores numbers from 0 to 255 and is useful when binary data must be edited. Beginners may use byte arrays while working with files, images, device data, or network information that needs modification before being saved or sent.

    Example: Change a byte array value

    # Create a byte array from three numbers.
    data = bytearray([65, 66, 67])
    
    # Change the second number.
    data[1] = 90
    
    print(data)
    print(data.decode("utf-8"))
    Output:
    bytearray(b'AZC')
    AZC

    Explanation: The number 66 represents the letter B. Replacing it with 90 changes the second letter to Z, so the decoded text becomes AZC.

    4.16 Memory Views

    A memory view lets Python access the memory of binary data without making a full copy. This can improve speed and reduce memory use when handling large byte arrays. It is an advanced feature, but beginners should understand that it provides a window into existing binary data rather than creating separate data.

    Example: View and change byte data

    # Create editable binary data.
    data = bytearray([10, 20, 30])
    
    # Create a memory view of the same data.
    view = memoryview(data)
    
    # Change the first value through the view.
    view[0] = 99
    
    print(list(data))
    Output:
    [99, 20, 30]

    Explanation: The memory view points to the same byte array. Changing the first item through view also changes the original data object.

    4.17 The None Type

    None represents the absence of a value. It is different from zero, an empty string, or False. Beginners use None when a value is not available yet, when a function has no result to return, or when a variable should clearly indicate that nothing has been assigned.

    Example: Store no value

    # No phone number is available yet.
    phone_number = None
    
    print(phone_number)
    print(type(phone_number))
    Output:
    None
    <class 'NoneType'>

    Explanation: The variable exists, but it currently holds no meaningful value. Python identifies None as the special NoneType data type.

    4.18 Mutable Data Types

    A mutable data type can be changed after it is created. Lists, dictionaries, sets, and byte arrays are common mutable types. This means items can be added, removed, or replaced without creating a completely new object. Beginners should be careful because changes may also be visible through other references to the same object.

    Example: Change a list item

    # Create a mutable list.
    colors = ["red", "blue", "green"]
    
    # Replace the second item.
    colors[1] = "yellow"
    
    print(colors)
    Output:
    ['red', 'yellow', 'green']

    Explanation: Lists are mutable, so the item at index 1 can be replaced. The original list is updated directly instead of creating a new list automatically.

    4.19 Immutable Data Types

    An immutable data type cannot be changed after it is created. Integers, floats, strings, tuples, bytes, and frozen sets are immutable. When beginners appear to change one of these values, Python actually creates a new object and assigns the variable to it. This behavior helps keep certain values predictable and safe.

    Example: Create a new string value

    # Create an immutable string.
    word = "cat"
    
    # This creates a new string and reassigns the variable.
    word = word + "s"
    
    print(word)
    Output:
    cats

    Explanation: Python does not change the original string object. It creates the new string "cats" and makes the variable word refer to that new value.

    4.20 Checking Types with type()

    The type() function tells you the exact data type of a value or variable. It is especially helpful for beginners who are learning how Python stores different kinds of information. You can use it while testing code, reading user input, debugging errors, or confirming that a conversion produced the expected type.

    Example: Display variable types

    # Create three different values.
    city = "Toronto"
    temperature = 22.5
    visitors = 120
    
    print(type(city))
    print(type(temperature))
    print(type(visitors))
    Output:
    <class 'str'>
    <class 'float'>
    <class 'int'>

    Explanation: The function reports that city is a string, temperature is a float, and visitors is an integer.

    4.21 Checking Types with isinstance()

    The isinstance() function checks whether a value belongs to a specific type and returns True or False. It is often more useful than comparing type() directly because it also works well with related classes. Beginners can use it to validate values before performing an operation.

    Example: Check whether a value is an integer

    # Store a student's age.
    age = 13
    
    # Check the data type.
    result = isinstance(age, int)
    
    print(result)
    Output:
    True

    Explanation: The value stored in age is an integer, so isinstance(age, int) returns the Boolean value True.

    4.22 Type Conversion

    Type conversion means changing a value from one data type to another. Python provides functions such as int(), float(), str(), list(), and tuple(). Conversion is important because values of different types cannot always be used together. Beginners often convert user input before doing calculations.

    Example: Convert an integer to a float

    # Start with an integer.
    number = 8
    
    # Convert it to a floating-point number.
    decimal_number = float(number)
    
    print(decimal_number)
    print(type(decimal_number))
    Output:
    8.0
    <class 'float'>

    Explanation: The float() function converts the integer 8 into the floating-point value 8.0. The new variable therefore has the float type.

    4.23 Implicit Conversion

    Implicit conversion happens automatically when Python changes one numeric type into another during an operation. For example, when an integer is added to a float, Python converts the integer to a float so the calculation can continue safely. Beginners do not need to write a conversion function for this common situation.

    Example: Add an integer and a float

    # Integer value.
    whole_number = 5
    
    # Floating-point value.
    decimal_number = 2.5
    
    # Python converts automatically.
    result = whole_number + decimal_number
    
    print(result)
    print(type(result))
    Output:
    7.5
    <class 'float'>

    Explanation: Python automatically treats the integer 5 as a float during the calculation. Therefore, the final result is 7.5 and its type is float.

    4.24 Explicit Conversion

    Explicit conversion happens when the programmer deliberately changes a value by calling a conversion function. This gives you control over the result. For example, you can turn a decimal into an integer, text into a number, or a tuple into a list. Some conversions may remove information, such as decimal digits.

    Example: Convert a float to an integer

    # Store a floating-point value.
    price = 9.99
    
    # Convert it to an integer.
    whole_price = int(price)
    
    print(whole_price)
    Output:
    9

    Explanation: The int() function removes the decimal part instead of rounding. Therefore, 9.99 becomes the integer 9.

    4.25 Converting Strings to Numbers

    Text entered with input() is always returned as a string. To perform arithmetic, beginners must convert numeric text using int() or float(). The text must contain a valid number. For example, "25" can become an integer, while "25.5" can become a float.

    Example: Convert numeric text

    # Store numbers as strings.
    age_text = "15"
    height_text = "1.72"
    
    # Convert the strings to numbers.
    age = int(age_text)
    height = float(height_text)
    
    print(age + 1)
    print(height)
    Output:
    16
    1.72

    Explanation: The string "15" becomes an integer, so Python can add 1. The string "1.72" becomes a floating-point number.

    4.26 Converting Numbers to Strings

    Numbers can be converted to strings with the str() function. This is useful when building messages, labels, file names, or text that combines words and numeric values. Python does not allow a string and number to be joined directly with the plus sign, so conversion prevents a type error.

    Example: Build a sentence with a number

    # Store a number.
    age = 12
    
    # Convert the number to text.
    message = "I am " + str(age) + " years old."
    
    print(message)
    Output:
    I am 12 years old.

    Explanation: The str() function changes the integer 12 into the text "12". Python can then join it with the other strings.

    4.27 Converting Collections

    Python can convert one collection type into another. For example, a tuple can become a list, a list can become a set, and a range can become a list. This is useful when beginners need different behavior, such as editing items in a list or removing duplicates by converting values to a set.

    Example: Convert a list to a set and tuple

    # Create a list with duplicate values.
    numbers = [1, 2, 2, 3]
    
    # Convert it to other collection types.
    unique_numbers = set(numbers)
    fixed_numbers = tuple(numbers)
    
    print(unique_numbers)
    print(fixed_numbers)
    Output:
    {1, 2, 3}
    (1, 2, 2, 3)

    Explanation: The set removes the duplicate 2 because sets keep unique values. The tuple keeps every original item and preserves their order.

    4.28 Type Conversion Errors

    A type conversion error occurs when Python cannot change a value into the requested type. For example, the word "hello" cannot become an integer. Beginners should validate input or use error handling before conversion. Reading the error message carefully helps identify the value and conversion that caused the problem.

    Example: Handle an invalid conversion

    # Store text that is not a valid integer.
    value = "hello"
    
    try:
        number = int(value)
        print(number)
    except ValueError:
        print("Please enter digits only.")
    Output:
    Please enter digits only.

    Explanation: The conversion fails because "hello" is not numeric text. The except ValueError block catches the error and displays a clear message instead of stopping the program.

    4.29 Introduction to Type Hints

    Type hints show the expected data type of variables, function parameters, and return values. They help readers understand code and help development tools find possible mistakes. Python usually does not enforce type hints while running the program, so they are guidance rather than strict rules. Beginners can use them to write clearer code.

    Example: Add type hints to a function

    # The function expects two integers
    # and returns an integer.
    def add_numbers(first: int, second: int) -> int:
        return first + second
    
    result = add_numbers(4, 6)
    print(result)
    Output:
    10

    Explanation: The type hints show that both parameters should be integers and that the function should return an integer. The function adds 4 and 6 to produce 10.

    4.30 Chapter Practice Exercises

    Practice exercises help beginners remember data types by using them in small tasks. Try creating integers, floats, strings, Booleans, lists, tuples, sets, and dictionaries. Also practice checking types and converting values. The example below combines several skills, but you should change the values and test your own versions afterward.

    Example: Practice several data types

    # Create different data types.
    student_name = "Lina"
    student_age = 13
    scores = [88, 91, 84]
    is_active = True
    
    # Calculate the average score.
    average = sum(scores) / len(scores)
    
    print("Name:", student_name)
    print("Age:", student_age)
    print("Average:", average)
    print("Active:", is_active)
    Output:
    Name: Lina
    Age: 13
    Average: 87.66666666666667
    Active: True

    Explanation: The example uses a string, integer, list, Boolean, and float result. The average is calculated by dividing the total score by the number of scores.

    4.31 Chapter Mini Project

    This mini project creates a simple student profile using several Python data types. It uses strings for text, an integer for age, a list for scores, a Boolean for enrollment status, and a dictionary to organize the information. It also calculates an average, giving beginners practice with collections and numeric operations.

    Example: Build a student profile

    # Create a student profile dictionary.
    student = {
        "name": "Daniel",
        "age": 14,
        "scores": [75, 82, 91],
        "enrolled": True
    }
    
    # Calculate the student's average score.
    average = sum(student["scores"]) / len(student["scores"])
    
    # Display the profile.
    print("Student Profile")
    print("Name:", student["name"])
    print("Age:", student["age"])
    print("Scores:", student["scores"])
    print("Average:", round(average, 2))
    print("Enrolled:", student["enrolled"])
    Output:
    Student Profile
    Name: Daniel
    Age: 14
    Scores: [75, 82, 91]
    Average: 82.67
    Enrolled: True

    Explanation: The dictionary keeps related student information together. The program reads the score list, calculates the average, rounds it to two decimal places, and prints every profile value clearly.

    Chapter 2: Development EnvironmentPrepare Your JavaScript Workspace

    A modern course built to help learners study step by step with clarity, comfort, and confidence.