Class XII Computer Science PT1 ALL STUDY MATERIAL

  • Data Types: Specifies the type of value a variable can store, influencing how the data is interpreted and the operations that can be performed on it. The type() function is used to identify a variable's data type during runtime, aiding in debugging and type checking.

    • Numeric Types:

      • Integers (int): Whole numbers without any decimal point (e.g., -3, 0, 150).

      • Floating-Point Numbers (float): Numbers with a decimal point (e.g., 3.14, -2.5, 0.0).

      • Complex Numbers (complex): Numbers with a real and imaginary part (e.g., 2 + 3j).

    • Text Type:

      • Strings (str): Sequences of characters enclosed in single quotes ('…') or double quotes ("…") (e.g., 'Hello', "Python").

    • Boolean Type:

      • Booleans (bool): Represents truth values, either True or False.

    • Sequence Types:

      • Lists (list): Ordered, mutable sequences of items (e.g., [1, 2, 'a']).

      • Tuples (tuple): Ordered, immutable sequences of items (e.g., (1, 2, 'a')).

      • Ranges (range): Sequences of numbers (e.g., range(1, 5)).

    • Set Types:

      • Sets (set): Unordered collections of unique items (e.g., {1, 2, 3}).

      • Frozen Sets (frozenset): Immutable version of sets.

    • Mapping Type:

      • **Dictionaries (dict): Collections of key-value pairs (e.g.,{'name': 'Alice', 'age': 30}).- Numbers, Strings, Booleans, Lists, Tuples, Sets, and Dictionaries are Python's built-in data types.

  • Python Tokens: The basic building blocks of a Python program, including keywords, identifiers, variables, comments and different operators.

    • Keywords: Reserved words with specific, predefined meanings in Python. Keywords are case-sensitive and must be used exactly as defined.

      • Examples: if, else, for, while, def, class, import, return, and, or, not, in, is, None, True, False.

    • Identifiers: Names used to identify variables, functions, classes, modules, or other objects in the program.

      • Rules:

        • Must start with a letter (uppercase or lowercase) or an underscore (_).

        • Can be followed by letters, numbers, or underscores.

        • Cannot start with a digit.

        • Can be of any length, but short, meaningful names are preferred for readability.

        • Cannot be a keyword.

        • Cannot contain special symbols (!, @, #, $, %, etc.).

        • Case-sensitive (e.g., myVar and myvar are treated as different identifiers).

    • Variables: Named storage locations in memory that hold values. Variables are identified by a name (identifier) and refer to an object in memory.

      • In Python, you don't need to explicitly declare the data type of a variable. The type is inferred based on the assigned value.

      • Example: x = 10 (x is an integer variable), message = "Hello" (message is a string variable).

    • Comments: Explanatory notes added to the source code to provide information to the reader. Comments are ignored by the Python interpreter and do not affect the execution of the program.

      • Single-line comments start with a # character. Anything following # on the same line is treated as a comment.

      • Multi-line comments are enclosed in triple quotes (''' or """). They can span multiple lines.

      • Comments are used to explain code logic, provide documentation, or temporarily disable code during debugging.

  • Mutable vs. Immutable Data Types: Understanding the mutability of data types is crucial for predicting how operations will affect program state and memory usage.

    • Mutable: Values can be changed after creation. When a mutable object is modified, its memory address remains the same.

      • Examples: Lists, Dictionaries, Sets.

    • Immutable: Values cannot be changed after creation. If you try to modify an immutable object, a new object is created with the updated value, and the original object remains unchanged.

      • Examples: Strings, Tuples, Numbers (integers, floats, complex numbers), Booleans, Frozen Sets.

  • Operators: Symbols that perform operations on values (operands). Operators are essential for performing calculations, comparisons, and logical operations in Python.

    • Arithmetic Operators: Used for performing mathematical calculations.

      • + (Addition): Adds two operands.

      • - (Subtraction): Subtracts the right operand from the left operand.

      • * (Multiplication): Multiplies two operands.

      • / (Division): Divides the left operand by the right operand (result is a float).

      • % (Modulus): Returns the remainder when the left operand is divided by the right operand.

      • // (Floor Division): Divides the left operand by the right operand and returns the integer part of the result (i.e., the quotient without the decimal part).

      • ** (Exponentiation): Raises the left operand to the power of the right operand.

    • Relational Operators: Used for comparing values.

      • == (Equal to): Returns True if the left operand is equal to the right operand, False otherwise.

      • != (Not Equal to): Returns True if the left operand is not equal to the right operand, False otherwise.

      • > (Greater Than): Returns True if the left operand is greater than the right operand, False otherwise.

      • < (Less Than): Returns True if the left operand is less than the right operand, False otherwise.

      • >= (Greater Than or Equal to): Returns True if the left operand is greater than or equal to the right operand, False otherwise.

      • <= (Less Than or Equal to): Returns True if the left operand is less than or equal to the right operand, False otherwise.

    • Logical Operators: Used for combining or modifying Boolean expressions.

      • and: Returns True if both operands are True, False otherwise.

      • or: Returns True if at least one of the operands is True, False otherwise.

      • not: Returns the opposite of the operand's truth value. If the operand is True, not returns False, and vice versa.

    • Assignment Operators: Used for assigning values to variables.

      • =: Assigns the value on the right to the variable on the left.

      • +=: Adds the value on the right to the variable on the left and assigns the result to the variable.

      • -=: Subtracts the value on the right from the variable on the left and assigns the result to the variable.

      • *=: Multiplies the variable on the left by the value on the right and assigns the result to the variable.

      • /=: Divides the variable on the left by the value on the right and assigns the result to the variable.

      • //=: Performs floor division on the variable on the left by the value on the right and assigns the result to the variable.

      • %=: Calculates the modulus of the variable on the left by the value on the right and assigns the result to the variable.

      • **=: Raises the variable on the left to the power of the value on the right and assigns the result to the variable.

    • Identity Operators: Used for comparing the memory locations of two objects.

      • is: Returns True if both operands refer to the same object in memory, False otherwise.

      • is not: Returns True if both operands do not refer to the same object in memory, False otherwise.

    • Membership Operators: Used for testing whether a value is a member of a sequence (e.g., string, list, tuple).

      • in: Returns True if the value is found in the sequence, False otherwise.

      • not in: Returns True if the value is not found in the sequence, False otherwise.

  • Type Conversion: The process of changing a value from one data type to another. Type conversion is essential for performing operations involving different data types.

    • Implicit (automatic) Type Conversion: Occurs automatically when Python converts one data type to another without explicit instructions from the programmer.

      • Example: When adding an integer to a float, Python automatically converts the integer to a float to perform the addition.

    • Explicit (manual) Type Conversion: Occurs when the programmer explicitly specifies the data type to which a value should be converted using built-in functions.

      • int(): Converts a value to an integer.

      • float(): Converts a value to a floating-point number.

      • str(): Converts a value to a string.

      • bool(): Converts a value to a Boolean.

      • list(): Converts a value to a list.

      • tuple(): Converts a value to a tuple.

      • set(): Converts a value to a set.

      • dict(): Converts a value to a dictionary (requires a sequence of key-value pairs).

  • Control Statements: Statements that control the flow of execution in a program. Control statements allow you to execute specific blocks of code based on conditions or repeat blocks of code multiple times.

    • Decision Making: Used for executing different blocks of code based on whether a condition is true or false.

      • if statement: Executes a block of code if a condition is true.

      • elif statement: Executes a block of code if the previous if or elif condition is false and the current condition is true.

      • else statement: Executes a block of code if all preceding if and elif conditions are false.

    • Iteration (Loops): Used for repeating a block of code multiple times.

      • while loop: Repeats a block of code as long as a condition is true.

      • for loop: Repeats a block of code for each item in a sequence (e.g., string, list, tuple, range).

    • Jump Statements: Used for altering the normal flow of execution in a loop.

      • break statement: Terminates the loop immediately and transfers control to the next statement after the loop.

      • continue statement: Skips the rest of the current iteration of the loop and continues with the next iteration.

      • pass statement: Does nothing. It is used as a placeholder when a statement is required syntactically but no code needs to be executed.

  • Strings: Sequences of characters, enclosed in single quotes ('…') or double quotes ("…"). Strings are used to represent text in Python.

    • Strings are immutable, meaning their values cannot be changed after creation. If you need to modify a string, you must create a new string with the desired changes.

    • Individual characters in a string can be accessed using indexing (positive or negative).

      • Positive indexing starts from 0 for the first character, 1 for the second character, and so on.

      • Negative indexing starts from -1 for the last character, -2 for the second-to-last character, and so on.

    • Slicing: Used to extract a portion (substring) of a string using the syntax string_name[start:stop:step].

      • start is the index of the first character to include in the slice (inclusive).

      • stop is the index of the character to exclude from the slice (exclusive).

      • step specifies the increment between characters in the slice. If omitted, the default step is 1.

    • [::-1] is a common slicing technique used to reverse a string.

    • Traversing: Iterating through characters in a string using for loops.

    • Operations:

      • Concatenation (+): Joining strings together to create a new string.

      • Replication (*): Repeating a string a specified number of times to create a new string.

      • Comparison (==, >, <, >=, <=): Comparing strings lexicographically based on the Unicode values of their characters.

      • Membership (in, not in): Checking if a substring is present in a string.

  • Built-in String Methods: Predefined functions that can be called on strings to perform various operations.

    • len(): Returns the length (number of characters) of the string.

    • title(): Converts the first character of each word in the string to uppercase and the remaining characters to lowercase (title case).

    • lower(): Converts all characters in the string to lowercase.

    • upper(): Converts all characters in the string to uppercase.

    • count(str,start, end): Counts the number of occurrences of a specified substring within the string.

    • find(str,start, end): Returns the index of the first occurrence of a specified substring in the string, or -1 if the substring is not found.

    • index(str,start, end): Similar to find(), but raises an exception if the substring is not found.

    • endswith(): Checks if the string ends with a specified substring and returns True if it does, False otherwise.

    • startswith(): Checks if the string starts with a specified substring and returns True if it does, False otherwise.

    • isalnum(): Returns True if all characters in the string are alphanumeric (letters or numbers), False otherwise.

    • islower(): Returns True if all characters in the string are lowercase, False otherwise.

    • isupper(): Returns True if all characters in the string are uppercase, False otherwise.

    • isspace(): Returns True if the string contains only whitespace characters (spaces, tabs, newlines), False otherwise.

    • istitle(): Returns True if the string is in title case, False otherwise.

    • lstrip(): Removes leading whitespace characters (spaces, tabs, newlines) from the left side of the string.

    • rstrip(): Removes trailing whitespace characters (spaces, tabs, newlines) from the right side of the string.

    • strip(): Removes leading and trailing whitespace characters (spaces, tabs, newlines) from both sides of the string.

    • replace(oldstr, newstr): Replaces all occurrences of a specified substring with another substring.

    • join(): Joins the elements of an iterable (e.g., list, tuple) into a single string, using the string as a separator.

    • partition(): Partitions the string into three parts based on the first occurrence of a specified separator substring. Returns a tuple containing the part before the separator, the separator itself, and the part after the separator.

    • split(): Splits the string into a list of substrings, using a specified delimiter substring as the separator.

  • Lists: Ordered sequences of heterogeneous elements. Lists are a versatile data structure in Python and are used to store collections of items.

    • Lists are mutable, meaning their elements can be changed after the list is created.

    • Elements in a list are accessed by their index, starting from 0 for the first element.

    • Creating Lists:

      • a = [34, 76, 11, 98]: Creates a list of integers.

      • b = ['s', 3, 6, 't']: Creates a list of mixed data types (string, integer).

      • d = []: Creates an empty list.

    • Creating Lists from Existing Sequences:

      • new_list_name = list(sequence/string): Creates a new list from an existing sequence (e.g., string, tuple).

    • Operations:

      • Concatenation (+): Combines two lists into a new list.

      • Replication (*): Repeats a list a specified number of times to create a new list.

      • Slicing: Extracts a portion of a list using the syntax list_name[start:end].

    • Manipulation:

      • Updating: Modifying elements in a list using slicing and assignment.

      • Deleting: Removing elements from a list using del list_name[index].

  • Built-in List Methods: Predefined functions that operate on lists.

    • len(): Returns the length (number of elements) of the list.

    • list(): Creates a new list from an iterable (e.g., tuple, string).

    • append(): Adds an element to the end of the list.

    • extend(): Appends elements from another iterable (e.g., list, tuple) to the end of the list.

    • insert(): Inserts an element at a specified index in the list.

    • count(): Returns the number of times a specified element appears in the list.

    • index(): Returns the index of the first occurrence of a specified element in the list.

    • remove(): Removes the first occurrence of a specified element from the list.

    • pop(): Removes and returns the element at a specified index in the list. If no index is specified, it removes and returns the last element.

    • reverse(): Reverses the order of elements in the list in-place (modifies the original list).

    • sort(): Sorts the elements of the list in-place (modifies the original list).

    • sorted(): Returns a new sorted list from the elements of the original list.

    • min(): Returns the smallest element in the list.

    • max(): Returns the largest element in the list.

    • sum(): Returns the sum of all elements in the list (only works for numeric elements).

  • Tuples: Ordered, immutable sequences of elements. Tuples are similar to lists but have the key difference that they cannot be modified after creation.

    • Tuples are declared using parentheses ().

  • Built-in Tuple Methods:

    • len(): Returns the length (number of elements) of the tuple.

    • tuple(): Creates a new tuple from an iterable (e.g., list, string).

    • count(): Returns the number of times a specified element appears in the tuple.

    • index(): Returns the index of the first occurrence of a specified element in the tuple.

    • sorted(): Takes element and return new sorted list

    • min(): Returns the smallest element in the tuple.

    • max(): Returns the largest element in the tuple.

    • sum(): Returns the sum of all elements in the tuple (only works for numeric elements).

  • Dictionaries: Unordered collections of key-value pairs. Dictionaries are used to store and retrieve data efficiently using keys.

    • Keys must be unique and immutable (strings, numbers, tuples, etc.).

    • Created with curly braces {}.

    • Accessing elements: dictionary_name[key].

    • Traversing: Iterating through keys, values, or both.

    • Adding elements: dictionary_name[new_key] = value.

    • Updating elements: dictionary_name[existing_key] = new_value.

    • Membership: in, not in (checks if keys are present).

  • Built-in Dictionary Methods:

    • len(): Returns the length or number of key: value pairs of the dictionary.

    • dict(): Creates a dictionary from a sequence of key-value pairs.

    • keys(): Returns a list of keys in the dictionary.

      -values(): Returns a list of values in the dictionary.

    • items(): Returns a list of tuples(key – value) pair.

    • get(): Returns the value corresponding to the key passed as the argument if the key is not present in the dictionary it will return None.

      -update(): Appends the key-value pair of the dictionary passed as the argument to the key- value pair of the given dictionary.

    • del(): Deletes the item with the given key.

      -clear(): Deletes or clear all the items of the dictionary.

  • Python Functions: A block of organized, reusable code that performs a specific task. Functions are essential for modularizing code and promoting code reuse.

    • Types:

      • Built-in functions (e.g., abs(), eval(), input(), print(), pow())

      • Functions defined in modules (e.g., load() and dump() from pickle)

      • User-defined functions

    • Defining:

      • Use the def keyword.

      • Syntax: def function_name([parameter list]):

    • Arguments/Parameters:

      • Positional Arguments: Arguments are passed based on the positional order.

      • Default Arguments: A default argument is an argument that assume a default value if a value is not provided in the function call statement.

      • Keyword Arguments: Providing Value can be provided by using their name instead of the position (order) in function call statement.

    • Scope:

      • Local: Declared inside a function, accessible only within the function.

      • Global: Declared outside all functions, accessible throughout the whole program.

    • Value Returning Function : A function may or may not return one or more values.

  • Exception Handling :

    • Exception: Contradictory or Unexpected situation or unexpected error, during program execution. Examples Divide by zero errors ,Accessing the elements of an array beyond its range,Invalid input,Hard disk crash, Opening a non-existent file, Heap memory exhausted.

    • Exception Handling: Way of handling anomalous situations in a program-run.

  • File Handling (Text Files):

    • Files are named locations on disk to store related information.

    • Types of File -Binary file store in the same format in which the information is held in memory while text file is usually considered as sequence of lines.

    • Open, Read, write and close: - The open() function is used to open an existing file or creating a new file where different modes - reading, writing or appending is granted.

      • The close() function breaks the link of the file-object and the file on the disk.

    • Reading/Writing Information:

      • read([n]): Reads n bytes or the entire file.

      • readline([n]): Reads a line of file or returns the first n characters of the next line.

      • readlines(): All lines are returned to a list.

      • write(string): Writes a string to the file.

      • writelines(list): Writes a list of strings to the file.

    • Modifying data--flush() function will be used to force Python to write the content

      • With strip() , lstrip()and rstrip() whitespaces can be removed while reading text file.

    • File pointer-Maintains a file pointer which gives the current position in the file where reading and writing operation is performed.

  • File Handling (Binary Files):

    • A Binary file is a file that contains information in the same format in which the information is held in memory, ie the file content that is returned to us is raw ( with no translation or specific encoding ).

      • File Handling consists of following three steps :

      a) Open the file.

      b) Process the file ie perform read or write operation.

      c) Close the file.

    • Pickle Module: Provides us, with the ability to serialize and de-serialize objects, ie to convert objects into bitstreams which can be stored into files and later be used to reconstruct the original objects.

  • Different Methods - 1-Read It opens a file in read mode. 2-write It opens a file in write mode. 3- append: It opens a file to add some data.- In order to modify data there are some more useful method -

    1- tell(): It returns us the current position of the file pointer.

    2- seek(): It moves the file pointer to the specified position.

    3- dump(): It writes the data*object into the binary file represented by the file*object.

    4- load(): It reads data from the binary file represented by file*object and stored into another handle store*object.

  • CSV Files:

    • CSV (Comma Separated Values) is a file format for data storage with one record on each line and each field is separated by comma.

    • CSV files are used to transfer tabular data with easy implement and parse with almost all existing applications. It is simple, human readable, smaller and faster to handle. However, it has no standara way to represent binary data , poor support of special characters and control characters.It allows to move most basic data only. Complex configurations cannot be imported and exported this way. It allows to move most basic data only. Complex configurations cannot be imported and exported this way.

  • Python Provides CSV module to work with csv file:

    • Main Functions are: reader(), writer(),DictReader(),DictWriter()

    reader() function - Takes a file object and returns a _csv.reader object that can be used to iterate over the contents of a CSV file.

    writer() function - Used to write data in a csv file and accepts the same argument as the reader() function but returns a writer object.

    • CSV has two main methods:- writerow() print record line by line

      • writerows()print all record at a time -Reading a CSV file with DictReader():- This function(DictReader) is working similar to reader(). This function return lines as a dictionary instead of list. DictReader*Object = csv.DictReader(file*obj)

  • Stack:

    • A linear data structure based on Last-In-First-Out (LIFO) principle.

    • Operations: PUSH (add to the top), POP (remove from the top).

    • Implemented using Lists.

    • Application: PUSH(Stk,ele) and POP(Stk)

      Data Structure: method of organising data in the