0% found this document useful (0 votes)
5 views

Introduction to Python Programming

The document provides a comprehensive introduction to Python, covering its features, data types, control structures, functions, and object-oriented programming concepts. It explains various data structures such as lists, tuples, sets, and dictionaries, along with their operations and methods. Additionally, it discusses file handling, serialization, and encoding/decoding in Python.

Uploaded by

sumanu888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Introduction to Python Programming

The document provides a comprehensive introduction to Python, covering its features, data types, control structures, functions, and object-oriented programming concepts. It explains various data structures such as lists, tuples, sets, and dictionaries, along with their operations and methods. Additionally, it discusses file handling, serialization, and encoding/decoding in Python.

Uploaded by

sumanu888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Introduction to Python

Features of Python
1. Easy to Learn: Python's simple syntax makes it beginner-friendly.
2. Interpreted: Code is executed line by line, simplifying debugging.
3. Object-Oriented: Supports object-oriented programming for code reuse.
4. Dynamic Typing: Variables don’t require explicit declaration of types.
5. Extensive Libraries: Provides a wide range of built-in modules for various functionalities.
6. Cross-Platform: Runs on different operating systems without modification.
7. High-Level Language: Abstracts complex hardware details.
8. Open Source: Free to use, modify, and distribute.
9. Multi-Paradigm: Supports procedural, object-oriented, and functional programming.
10. Automatic Memory Management: Handles memory allocation and deallocation internally.

Variables and Identifiers


• Variables: Named storage locations for data, which can hold values and are mutable.
• Identifiers: Names given to variables, functions, or classes. They must start with a letter or underscore, are case-
sensitive, and cannot use reserved keywords.

Operators and Expressions


• Operators: Symbols used to perform operations on variables and values. They are categorized as arithmetic,
relational, logical, bitwise, assignment, membership, and identity operators.
• Expressions: Combinations of values, variables, and operators that result in a value.

Decision Making and Repetition


if, if-else, and nested if-else
• if: Executes a block of code when a condition is true.
• if-else: Executes one block of code if the condition is true and another block if false.
• Nested if-else: Allows conditional statements within another conditional.

else if (elif)
• Simplifies multiple conditions by chaining them into a single structure.

Loops
• while loop: Repeats a block of code as long as the condition is true.
• for loop: Iterates over a sequence like a list, string, or range.
• Nested loops: Loops placed within another loop for more complex iterations.

Control Statements
• break: Terminates the loop prematurely.
• continue: Skips the current iteration and moves to the next.
• pass: A null statement used as a placeholder, performing no operation.

Functions
Definition
• Functions are blocks of code designed to perform specific tasks. They promote code reuse and modularity.

Function Call
• The process of invoking a function to execute its code.

More on Defining Functions


• Functions can take arguments (parameters) and return values, making them flexible and reusable.
Recursive Functions
• Functions that call themselves to solve problems in smaller, simpler steps, commonly used in scenarios like
factorial or Fibonacci series calculations.

Strings
Introduction
• A string is a sequence of characters enclosed in single, double, or triple quotes.
• Strings are immutable, meaning their content cannot be changed after creation.

Accessing Strings
• Characters in a string can be accessed using indexing (positive and negative).
• Strings also support slicing to extract substrings.

Basic Operations
• Common operations include concatenation (+), repetition (*), and membership tests (in and not in).
• Strings also support comparison operators (==, <, >).

String Slicing
• String slicing extracts a portion of the string using the syntax string[start:end:step].
• Defaults: start=0, end=len(string), step=1.

String Functions and Methods


• Functions: Built-in functions like len(), max(), min(), and sorted().
• Methods: Specific to strings, such as:
o Case Conversion: upper(), lower(), capitalize(), title().
o Search and Replace: find(), rfind(), replace().
o Validation: isalpha(), isdigit(), isalnum(), isspace().
o Formatting: join(), split(), strip(), format().

Regular Expressions
• Regular expressions (regex) are patterns used to match, search, or manipulate strings.
• Python provides the re module to work with regex.
• Common functions:
o re.match(): Matches a pattern at the start of a string.
o re.search(): Searches for a pattern anywhere in a string.
o re.findall(): Finds all occurrences of a pattern.
o re.sub(): Replaces occurrences of a pattern.

Lists and Plotting


Introduction
• A list is an ordered, mutable collection of elements, which can be of different data types.
• Lists are created using square brackets [].

Operations on Lists
• Basic operations include:
o Indexing and Slicing: Accessing or modifying specific elements or sublists.
o Concatenation and Repetition: Combining lists or repeating elements.

Nested Lists
• Lists can contain other lists as elements, forming multi-dimensional structures like matrices.
List Methods
• Common methods:
o append(): Adds an element at the end.
o extend(): Adds all elements of another list.
o insert(): Inserts an element at a specific position.
o remove(): Removes the first occurrence of a value.
o pop(): Removes and returns an element by index.
o sort(): Sorts the list in ascending order.
o reverse(): Reverses the list.

List Comprehension
• A concise way to create lists using a single line of code.
• Syntax: [expression for item in iterable if condition].

Functional Programming
• filter(): Filters elements based on a condition.
• map(): Applies a function to each element in an iterable.
• reduce(): Applies a function cumulatively to elements in an iterable (requires the functools module).

Plotting Data in Lists


• matplotlib: A library for creating static, interactive, and animated plots.
o Commonly used functions:
▪ plot(): Plots a line graph.
▪ scatter(): Creates a scatter plot.
▪ bar(): Creates a bar chart.
▪ hist(): Creates a histogram.
• SciPy: A library for scientific computing. It complements matplotlib with additional tools for data analysis and
plotting.

NumPy Arrays Basics


Importing NumPy
• NumPy (Numerical Python) is a Python library used for numerical computing.
• It is imported using the command: import numpy as np.

Basic Array Attributes and Operations


• Attributes:
o ndim: Number of dimensions of the array.
o shape: Dimensions of the array (rows, columns).
o size: Total number of elements in the array.
o dtype: Data type of the elements.
• Operations:
o Includes element-wise operations such as addition, subtraction, multiplication, division, and
broadcasting (operations between arrays of different shapes).

1-D and Multi-Dimensional Arrays


• 1-D Arrays: Represent a single row of elements.
o Example: [1, 2, 3, 4].
• Multi-Dimensional Arrays: Arrays with two or more dimensions, represented as matrices or tensors.

Array Slicing and Striding


• Slicing: Extracts a portion of an array using the syntax array[start:stop:step].
• Striding: Specifies the step size for slicing. A step of 2 skips every other element.
Other Array Creation Functions
• Zeros and Ones: Create arrays filled with 0s or 1s.
o np.zeros((rows, cols))
o np.ones((rows, cols))
• Arange: Creates an array with evenly spaced values within a range.
o np.arange(start, stop, step)
• Linspace: Generates a specified number of evenly spaced values between two endpoints.
o np.linspace(start, stop, num)
• Eye and Identity: Create identity matrices.

Basic Array Math


• Supports vectorized operations:
o Element-wise operations: +, -, *, /.
o Aggregate functions: sum(), mean(), min(), max().
o Linear algebra operations using np.linalg.

Creating Matrices Using NumPy Arrays


• A matrix is a 2-dimensional array created using np.array() or other array creation functions.
• Matrices support operations like addition, multiplication, transposition, and inversion.

Accessing Elements
• Access individual elements using indexing, e.g., array[row, column].

Accessing Rows and Columns


• Rows: Use array[row, :] to access all columns of a specific row.
• Columns: Use array[:, column] to access all rows of a specific column.

Setting Elements
• Modify specific elements using indexing, e.g., array[row, column] = value.

Setting Rows and Columns


• Entire rows or columns can be set using slicing:
o Rows: array[row, :] = new_row
o Columns: array[:, column] = new_column

Multi-Dimensional Slicing and Striding


• Multi-Dimensional Slicing: Extracts sub-arrays by specifying ranges for multiple axes.
o Syntax: array[start1:stop1, start2:stop2]
• Striding: Allows stepping through an array while slicing, e.g., array[start1:stop1:step1, start2:stop2:step2].

Tuples

Introduction
• A tuple is an ordered, immutable collection of elements, defined using parentheses ().
• Unlike lists, tuples cannot be modified after creation, making them suitable for storing read-only data.

Operations on Tuples
• Indexing: Access elements using their index.
• Slicing: Extract portions of the tuple using the syntax tuple[start:end:step].
• Concatenation: Combine tuples using the + operator.
• Repetition: Repeat elements using the * operator.
• Membership Test: Check if an element exists using in or not in.

Packing and Unpacking


• Packing: Assign multiple values into a single tuple.
o Example: t = (1, 2, 3)
• Unpacking: Extract tuple elements into separate variables.
o Example: a, b, c = t

Nested Tuples
• Tuples can contain other tuples or collections as elements, allowing for multi-level data representation.

Tuple Methods and Functions


• Tuples have limited methods due to immutability:
o count(): Returns the count of a specified element.
o index(): Returns the index of the first occurrence of a specified element.
• Built-in Functions:
o len(), max(), min(), sum(): Perform basic operations on tuple elements.

Set
Introduction
• A set is an unordered, mutable collection of unique elements, defined using curly braces {} or the set() function.
• Sets do not allow duplicate elements.

Set Operations
• Basic Operations:
o Add elements: add().
o Remove elements: remove(), discard(), pop().
• Mathematical Operations:
o Union: Combines elements from two sets (| or union()).
o Intersection: Finds common elements (& or intersection()).
o Difference: Finds elements in one set but not the other (- or difference()).
o Symmetric Difference: Finds elements in either set but not both (^ or symmetric_difference()).
• Subset and Superset:
o Check subset: issubset().
o Check superset: issuperset().

Dictionaries
Introduction
• A dictionary is an unordered collection of key-value pairs, defined using curly braces {} with keys and values
separated by a colon (:).
• Keys must be unique and immutable, while values can be of any type.

Basic Operations
• Accessing Values: Use keys to retrieve values (dict[key]).
• Adding/Updating: Assign a value to a key (dict[key] = value).
• Removing Items: Use methods like pop(), popitem(), or del.
• Checking Keys: Use the in operator to check if a key exists.

Sorting Items
• Use the sorted() function to sort keys or items in a dictionary.
• Sorting can be done by keys or values.

Looping Over Dictionary


• Loop through:
o Keys: for key in dict.
o Values: for value in dict.values().
o Key-Value pairs: for key, value in dict.items().

Nested Dictionaries
• Dictionaries can contain other dictionaries as values, allowing for hierarchical data representation.

Built-In Dictionary Functions


• Common functions include:
o len(): Returns the number of items.
o keys(): Returns a view of keys.
o values(): Returns a view of values.
o items(): Returns a view of key-value pairs.
o clear(): Removes all items.
o copy(): Creates a shallow copy.

OOPS Concepts
Introduction
• Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, promoting
modularity, reusability, and abstraction.
• Key principles:
o Encapsulation: Hiding the internal details of an object and exposing only essential features.
o Inheritance: Reusing and extending functionality by deriving classes from existing ones.
o Polymorphism: Performing a single action in multiple ways, such as method overriding and operator
overloading.
o Abstraction: Representing essential features without detailing the implementation.

Classes and Objects


• Class: A blueprint for creating objects. Defines properties (attributes) and behaviors (methods).
• Object: An instance of a class. Represents specific data and behaviors defined by its class.

Class Method and self-Argument


• Class Method:
o Defined using the @classmethod decorator.
o Takes cls as its first parameter, which refers to the class itself.
o Used to access or modify class-level data.
• self-Argument:
o Refers to the current instance of the class.
o Used to access instance variables and methods within the class.
The __init__() Method
• A special method called the constructor, automatically executed when an object is created.
• Initializes the object's attributes.
• Syntax:
• def __init__(self, parameters):
• # Initialize attributes

Class Variables and Object Variables


• Class Variables:
o Shared across all instances of a class.
o Declared within the class but outside any method.
• Object Variables:
o Specific to each instance.
o Declared within methods, typically inside __init__().

Public and Private Data Members


• Public Data Members:
o Accessible from anywhere in the program.
o Defined without any prefix.
• Private Data Members:
o Restricted access to within the class.
o Defined with a double underscore prefix (__).
o Name mangling is applied to ensure privacy.

Inheritance
• Allows a class (child) to inherit properties and methods from another class (parent).
• Types of inheritance:
o Single Inheritance: One child inherits from one parent.
o Multiple Inheritance: A child inherits from multiple parents.
o Multilevel Inheritance: Inheritance across multiple levels.
o Hierarchical Inheritance: Multiple children inherit from one parent.
o Hybrid Inheritance: A combination of two or more types of inheritance.
• super(): A method used to call the parent class's methods or constructor.

Operator Overloading
• Enables customizing the behavior of operators for user-defined types.
• Achieved by defining special methods (magic methods) in the class:
o __add__(): For + operator.
o __sub__(): For - operator.
o __mul__(): For * operator.
o __eq__(): For == operator.
o Other methods like __lt__(), __gt__(), and __str__() can also be overloaded.
Files and Exceptions
Reading and Writing Files
• Opening Files: Files are opened using the built-in open() function.
o Syntax: open('filename', 'mode')
o Modes include:
▪ 'r': Read (default).
▪ 'w': Write (creates a new file or truncates an existing file).
▪ 'a': Append.
▪ 'b': Binary mode (e.g., 'rb' for reading binary).
▪ 'x': Exclusive creation (fails if the file exists).
• Reading Files:
o read(): Reads the entire file content.
o readline(): Reads one line at a time.
o readlines(): Returns a list of all lines.
• Writing Files:
o write(): Writes a string to the file.
o writelines(): Writes a list of strings.
• Closing Files: Always close files after operations using file.close() to ensure data is saved and resources are
freed.

Serialization using JSON and Pickle


• JSON (JavaScript Object Notation):
o A lightweight data interchange format that stores data in key-value pairs.
o Serialization (converting Python objects into JSON) and Deserialization (converting JSON back into
Python objects) are done with the json module.
o Functions:
▪ json.dump(obj, file): Serializes an object and writes it to a file.
▪ json.load(file): Deserializes JSON data from a file.
▪ json.dumps(obj): Converts an object to a JSON string.
▪ json.loads(json_string): Converts a JSON string back to an object.
• Pickle:
o A Python-specific format for serializing and deserializing objects, useful for saving Python-specific
objects like functions or class instances.
o Functions:
▪ pickle.dump(obj, file): Serializes an object and writes it to a file.
▪ pickle.load(file): Deserializes data from a file into a Python object.

Encoding and Decoding


• Encoding: Converting strings into a byte representation (e.g., UTF-8 encoding).
o str.encode(encoding) method is used.
• Decoding: Converting byte representations back into strings.
o bytes.decode(encoding) method is used.
• Encoding is commonly used when reading/writing files in binary or when working with web data (like HTTP).

Handling Exceptions
• Exceptions are runtime errors that occur during program execution, and Python provides a robust mechanism
for handling them.
• Try-Except Block: Handles exceptions without crashing the program.
o Syntax:
Multiple Excepts: Multiple specific exceptions can be handled.
• Else Block: Runs if no exception occurs in the try block.
• Finally Block: Always runs, whether an exception occurs or not (typically used for cleanup).

Assertions
• Assertions are used to test conditions during development. If the condition evaluates to False, an AssertionError
is raised.
• Syntax:
• Assertions are generally used for debugging, checking assumptions in the code.

Modules: Math, Random, Calendar, Turtle


Math Module
• Provides mathematical functions such as:
o math.sqrt(x): Square root of x.
o math.pow(x, y): x raised to the power of y.
o math.factorial(x): Factorial of x.
o math.pi: Value of π (Pi).
o math.sin(x), math.cos(x): Trigonometric functions.
Random Module
• Provides functions for generating random numbers.
o random.random(): Returns a random float between 0 and 1.
o random.randint(a, b): Returns a random integer between a and b.
o random.choice(sequence): Chooses a random element from a sequence.
o random.shuffle(sequence): Shuffles the sequence in place.
Calendar Module
• Provides functions to work with dates and calendars.
o calendar.month(year, month): Returns a string representing the calendar for the given month.
o calendar.isleap(year): Checks if the year is a leap year.
o calendar.weekday(year, month, day): Returns the day of the week for a given date.
Turtle Module
• A graphical module used for creating drawings and animations.
• Provides a turtle that can be controlled using functions like:
o turtle.forward(distance): Moves the turtle forward by a specified distance.
o turtle.left(angle): Turns the turtle by a specified angle.
o turtle.color(color): Changes the turtle’s drawing color.
o turtle.done(): Ends the turtle graphics.

Built-In and User-Defined Exceptions


• Built-In Exceptions:
o Examples: ValueError, TypeError, IndexError, FileNotFoundError, etc.
o These exceptions are pre-defined and can be used to catch common errors.
• User-Defined Exceptions:
o Custom exceptions can be created by inheriting from the base Exception class.
o Syntax:

You might also like