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

Unit - 1

The document discusses Python basics including why Python is used, its features, objects, data types, and built-in functions. Python is an interpreted, interactive, object-oriented scripting language that is easy to learn and use. It supports various data types like integers, floats, strings, lists, dictionaries and built-in functions for common operations. Python uses object-oriented programming and all entities in Python like variables, lists, functions etc. are considered objects having attributes and methods.

Uploaded by

160421748035
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)
16 views

Unit - 1

The document discusses Python basics including why Python is used, its features, objects, data types, and built-in functions. Python is an interpreted, interactive, object-oriented scripting language that is easy to learn and use. It supports various data types like integers, floats, strings, lists, dictionaries and built-in functions for common operations. Python uses object-oriented programming and all entities in Python like variables, lists, functions etc. are considered objects having attributes and methods.

Uploaded by

160421748035
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/ 21

Unit – 1

Chapter -1
Topic – Python Basics
Python is a high level interpreted interactive and object-oriented scripting
language.
Python is designed to be highly readable because it uses English keywords
frequently whereas other languages use punctuations.
why do we use it:
 Python is interpreted – python is processed at run time by the
interpreter, you don’t have to need to compile your programs before
executing it.
 Python is interactive – You can directly write your python program at
python prompt.
 Python is Object – Oriented – It uses programming technique that
encapsulates code within objects.
 Python is Beginner’s Language - It has a simple syntax and it is easy to
learn.
Features of python:
 Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax.
 Easy-to-read − Python code is more clearly defined and uses English like
language.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable
and cross-platform compatible on UNIX, Windows, and MacOS.
 Interactive Mode − Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and
has the same interface on all platforms. The code written in any other OS
can run on any other OS.
 Extendable − You can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
 Databases − Python provides interfaces to all major commercial
databases.
 GUI Programming − Python supports GUI applications that can be
created and ported to many system calls, libraries and windows systems.
 Scalable − Python provides a better structure and support for large
programs than shell scripting.

Topic – Python Objects


Python uses the object model abstraction for data storage. Any construct that
contains any type of value is an object. Although Python is classified as an
"object-oriented programming (OOP) language, you can certainly write a useful
Python script without the use of classes and instances.
All Python objects have the following three characteristics: an identity, a type,
and a value.
1) IDENTITY: Is a unique identifier that differentiates an object from all others.
Any object's identifier can be obtained using the id() built-in function.
2) TYPE: An object's type indicates what kind of values an object can hold,
what operations can be applied to such objects, and what behavioural rules
these objects are subjected to. You can use the type() BIF to reveal the type of
a Python object.
3) VALUE: Is data item that is represented by an object, All three are assigned
on object creation and are read-only with one exception, that is the value that
means value supports updation, When an object's value can be changed it is
known as an object's mutability.
Python supports a set of basic (built-in) data types, as well as some auxiliary
types, Most applications generally use the standard types and create and
instantiate classes for all specialized data storage.
Object Attributes:
An object attribute refers to a variable or piece of data that is associated with
an object. Objects are instances of classes, and classes define the structure
and behaviour of objects. Object attributes are essentially variables that
belong to an object and store data specific to that object.
Commonly used object attributes are:
 doc : This attribute stores the docstring (documentation string) of a
function
 class : This attribute returns the class to which an object belongs.
 init : This is the constructor method in a class, automatically called
when an object is created from that class. It initializes the object's
attributes and sets its initial state.

Topic – Standard Types(Data types)


Standard types are also know’ s as primitive data types, this standard types
provide the basic building blocks for working with data in Python. Some of
the standard types are as follows:
 Numeric Types:
 int: Integer data type, representing whole numbers.
 float: Floating-point data type, representing real numbers with
decimal points.
 complex: Complex number data type, representing numbers with real
and imaginary parts.
 Sequence Types:
 str: String data type, representing text.
 list: List data type, representing ordered collections of items.
 tuple: Tuple data type, representing ordered, immutable collections
of items.
 Mapping Type:
 dict: Dictionary data type, representing key-value mappings.
 Set Types:
 set: Set data type, representing an unordered collection of unique
items.
 frozenset: An immutable version of the set data type.
 Boolean Type:
 bool: Boolean data type, representing either True or False.
 None Type:
 NoneType: Represents a special value None, often used to indicate
the absence of a value or a null value.

Topic – Other Build in types


 Bytes: Represents a sequence of bytes, often used to work with binary
data or encode text in different character encodings.
 Bytearray: Similar to bytes, but mutable. You can modify the contents of
a bytearray.
 Range: Represents a sequence of numbers, often used in for loops and
iteration.

Topic – Internal types


Internal Types are as follows:
 Code:
Code objects are executable pieces of Python source that are byte-
compiled, usually return values from calling the compile() BIF, Code
objects themselves do not contain any information regarding their
execution environment, but they are at the heart of every user-
defined function, all of which do contain some execution context.
 Frame:
These are objects representing execution stack frames in Python.
Frame objects contain all the information the Python interpreter
needs to know during a runtime execution environment. Each
function call results in a new frame object, and for each frame
object, a C stack frame is created as well.
 Traceback:
When you make an error in Python, an exception is raised. If
exceptions are not caught or "handled," the interpreter exits with
some diagnostic information, The traceback object is just a data item
that holds the stack trace information for an exception and is
created when an exception occurs.
 Slice:
Slice objects are created using the Python extended slice syntax. This
extended syntax allows for different types of indexing. These various
types of indexing include stride indexing, multi-dimensional indexing,
and indexing using the Ellipsis type
 Ellipsis:
Ellipsis objects are used in extended slice notations, Like the Null
object None, ellipsis objects also have a single name, Ellipsis, and
have a Boolean True value at all times.
 XRange:
XRange objects are created by the BIF xrange(), a sibling of the
range() BIF, and used when memory is limited and when range()
generates an unusually large data set.

Topic – standard type operations


Object value comparison:
 Comparison operators are used to determine equality of two data
values between members of the same type.
 These comparison operators are supported for all built-in types.
 Comparisons yield Boolean True or False values, based on the validity of
the comparison expression.

Object Identity Comparison:


 In addition to value comparisons, Python also supports the notion of
directly comparing objects themselves.
 Objects can be assigned to other variables (by reference). Because each
variable points to the same (shared) data object, any change effected
through one variable will change the object and hence be reflected
through all references to the same object.
 Example 1: foo1 and foo2 reference the same object
foo1 = foo2 = 4.3
 Example 2: foo1 and foo2 reference the same object
foo1 = 4.3 foo2 = foo1
 Example 3: foo1 and foo2 reference different objects
foo1 = 4.3
foo2 = 1.3 + 3.0
 The object identity comparison operators all share the same precedence
level and are presented in Table
Standard Type Object Identity Comparison Operators:

Standard Type Boolean Operators:


Expressions may be linked together or negated using the Boolean logical
operators and, or, and not, all of which are Python keywords.
The not operator has the highest precedence following AND and then OR
operator

Topic - Standard Type Build-in Functions


Python provides a wide range of built-in functions that are commonly used for
various operations on standard data types.
These functions are part of the Python standard library and can be used
without the need for additional imports.
Here are some of the standard built-in functions in Python:
1. len(): Returns the length (the number of items) of an iterable, such as a
list, tuple, string, or dictionary.
2. type(): Returns the data type or class of an object.
3. int(): Converts a value to an integer.
4. float(): Converts a value to a floating-point number.
5. str(): Converts a value to a string.
6. list(): Converts an iterable to a list.
7. tuple(): Converts an iterable to a tuple.
8. dict(): Creates a dictionary from key-value pairs.
9. max(): Returns the maximum element from an iterable
10.min(): Returns the minimum element from an iterable
11.sum(): Returns the sum of all elements in an iterable.
12.range(): Generates a sequence of numbers.
13.input(): Reads a line of text from the user.
14.print(): Prints output to the console.

Topic – Categorizing the standard types


standard types can be categorized into several fundamental categories based
on their characteristics and usage. Here are the primary categories for standard
types in Python:
Numeric Types:
 int: Represents integers (whole numbers).
 float: Represents floating-point numbers (real numbers with a decimal
point).
 complex: Represents complex numbers with real and imaginary parts.
Sequence Types:
 str: Represents strings of characters.
 list: Represents ordered, mutable (changeable) sequences.
 tuple: Represents ordered, immutable (unchangeable) sequences.
 range: Represents immutable sequences of numbers used for iteration.
Mapping Types:
 dict: Represents dictionaries, which are unordered collections of key-
value pairs.
Set Types:
 set: Represents unordered, mutable sets containing unique elements.
 frozenset: Represents unordered, immutable sets containing unique
elements.
Boolean Type:
 bool: Represents Boolean values (True or False).
Binary Types (Bytes and Byte Arrays):
 bytes: Represents sequences of bytes (immutable).
 bytearray: Represents sequences of bytes (mutable).
None Type:
 None: Represents a special value indicating the absence of a value.
Callable Types:
 function: Represents user-defined or built-in functions.
 method: Represents functions defined within classes.
 class: Represents user-defined or built-in classes.

Topic – Unsupported Type


In Python, there are certain types of data that are not directly supported or
have limited support because they are not part of the core language or
standard library. These unsupported types may require additional libraries or
custom implementations to work with.
Examples of Unsupported Types are as follows:
1. Pointers and References: Python does not have explicit pointer types like
some other languages (e.g., C++). Python manages memory and
references automatically, so you don't need to deal with memory
addresses directly.
2. Arrays: Python lists are similar to arrays, but they can hold elements of
different types and have dynamic sizing.
3. Structs and Unions: Python does not have built-in support for creating
low-level data structures like structs and unions. You can use classes to
define custom data structures with attributes.
4. Enumerations (Enums): While Python does have an enum module that
allows you to create enumerations, enums are not a core language
feature. You need to import and use the enum module to define
enumerations.
5. Union Types: Python does not natively support union types that can hold
different types of values at different times. You typically use
polymorphism and dynamic typing to achieve similar behavior.
Chapter – 2

Topic – Introduction to numbers


 Numbers are a fundamental data type used for performing various
mathematical operations.
 Python supports different types of numbers, including integers, floating-
point numbers, and complex numbers.
 you can create, assign, update, and remove numbers using variables.
Creating and Assigning Numbers:
 To create and assign a number to a variable, you simply use the
assignment operator (=) and provide the value you want to store in the
variable.
 Python will automatically determine the type of the number (integer,
floating-point, or complex) based on the value you assign.
Example demonstration of creating and assigning numbers:
 # Creating and assigning an integer
x=5
 # Creating and assigning a floating-point number
pi = 3.14159
 # Creating and assigning a complex number
z = 1 + 2j
Updating Numbers:
 You can update the value of a number by reassigning a new value to
the variable holding that number.
 Python allows you to perform arithmetic operations and update
variables in various ways.
Example of demonstration:
 # Update an integer
x = x + 1 # Increment x by 1
 # Update a floating-point number
pi = pi * 2 # Double the value of pi
 # Update a complex number
z = z * (3 + 4j) # Multiply z by another complex number

Removing Numbers:
 In Python, you don't explicitly remove numbers; instead, you can delete
the variable holding the number using the del statement.
 When you delete a variable, it removes the reference to the number,
and if there are no other references to that number, it becomes eligible
for garbage collection.
 After deleting a variable, you won't be able to access its value, and
attempting to do so will result in a NameError because the variable no
longer exists.
Example of demonstration:
 x = 5 # Create and assign a number
del x # Delete the variable x (number is removed if no other references
exist)

Topic – Integers, Floating point real number, complex


number.
 Integers (int):
o Integers are whole numbers without a decimal point.
o Examples: -3, 0, 42, 1001, etc.
o In Python, you can declare an integer simply by assigning a whole
number to a variable.
o Here is the example code:
x=5
y = -10
 Floating-Point Numbers (float):
o Floating-point numbers represent real numbers with a decimal
point.
o Examples: 3.14, -0.5, 2.0, 1e-3, etc.
o You can declare a floating-point number by using a decimal point.
o Here is the example code:
pi = 3.14159
price = 9.99
 Complex Numbers (complex):
o Complex numbers consist of a real part and an imaginary part,
expressed as a + bj, where a is the real part, and b is the imaginary
part.
o Example: 3 + 2j
o You can declare a complex number by using the j or J suffix for the
imaginary part.
o Here is the example code:
z = 1 + 2j

Topic – Operators
In Python, you can perform various operations on numbers using operators.
These operators allow you to perform arithmetic calculations, comparisons,
and other manipulations on numeric values.
Arithmetic Operators:
Arithmetic operators are used for performing mathematical operations on
numbers.
o Addition +: Adds two numbers together.
Example code:
result = 5 + 3 # Result is 8
o Subtraction -: Subtracts the right operand from the left operand.
result = 8 - 3 # Result is 5
o Multiplication *: Multiplies two numbers.
result = 4 * 6 # Result is 24
o Division /: Divides the left operand by the right operand. The result is a
float.
result = 15 / 2 # Result is 7.5
o Integer Division //: Performs floor division, discarding the remainder to
return an integer result.
result = 15 // 2 # Result is 7
o Modulo %: Returns the remainder of the division of the left operand by
the right operand.
remainder = 15 % 2 # Result is 1
o Exponentiation **: Raises the left operand to the power of the right
operand.
result = 2 ** 3 # Result is 8
Comparison Operators:
Comparison operators are used to compare two numbers and return a Boolean
result (True or False).
 Equal ==: Checks if two values are equal.
result = (5 == 5) # Result is True
 Not Equal !=: Checks if two values are not equal.
result = (5 != 3) # Result is True
 Greater Than >: Checks if the left operand is greater than the right
operand.
result = (8 > 5) # Result is True
 Less Than <: Checks if the left operand is less than the right operand.
result = (3 < 5) # Result is True
 Greater Than or Equal To >=: Checks if the left operand is greater than or
equal to the right operand.
result = (5 >= 5) # Result is True
 Less Than or Equal To <=: Checks if the left operand is less than or equal
to the right operand.
result = (3 <= 5) # Result is True
Logical Operators:
Logical operators are used to combine or manipulate Boolean values.
 and: Returns True if both operands are True.
result = (True and False) # Result is False
 or: Returns True if at least one operand is True.
result = (True or False) # Result is True
 not: Returns the opposite of the operand's value.
result = not True # Result is False
Bitwise Operators:
 Bitwise operators in Python are used to perform
operations on the individual bits of integers.
 These operators work directly with the binary
representation of the numbers.
 The bitwise operators include:

 AND (&): It performs a bitwise AND operation. It


sets each bit to 1 if both bits are 1.
 OR (|): It performs a bitwise OR operation. It sets
each bit to 1 if any of the two bits is 1.
 XOR (^): It performs a bitwise XOR (exclusive OR)
operation. It sets each bit to 1 if exactly one of the
two bits is 1.
 NOT (~): It performs a bitwise NOT operation. It
flips the bits, i.e., it changes 1 to 0 and 0 to 1.
 Left shift (<<): It shifts the bits of the number to
the left by the specified number of positions. The
leftmost bits are discarded, and the rightmost bits
are filled with 0.
 Right shift (>>): It shifts the bits of the number to
the right by the specified number of positions. The
rightmost bits are discarded, and the leftmost bits
are filled according to the sign bit (0 for non-
negative numbers, 1 for negative numbers).
Topic – Build in functions
Python provides a variety of built-in functions for working with numbers. These
functions allow you to perform various mathematical operations, conversions,
and manipulations on numeric values.

1-> Mathematical Functions:


 abs(): Returns the absolute value of a number.
absolute_value = abs(-5) # Result is 5
 max(): Returns the maximum value among multiple arguments or
elements in an iterable.
max_value = max(10, 20, 5) # Result is 20
 min(): Returns the minimum value among multiple arguments or
elements in an iterable
min_value = min(10, 20, 5) # Result is 5
 sum(): Returns the sum of all elements in an iterable.
total = sum([1, 2, 3, 4, 5]) # Result is 15
2- > Type Conversion Functions:

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


integer_value = int(3.5) # Result is 3
 float(): Converts a value to a floating-point number.
float_value = float("3.14") # Result is 3.14
 complex(): Creates a complex number from real and imaginary parts.
complex_number = complex(1, 2) # Result is 1+2j
 str(): Converts a value to a string.
str_value = str(42) # Result is the string "42"
3-> Rounding Functions:
 round(): Rounds a floating-point number to the nearest integer or a
specified number of decimal places.
rounded_value = round(3.14159, 2) # Result is 3.14
 ceil(): Returns the smallest integer greater than or equal to a number.
import math
ceiling_value = math.ceil(4.2) # Result is 5
 floor(): Returns the largest integer less than or equal to a number.
import math
floor_value = math.floor(4.9) # Result is 4
4-> Exponential and Logarithmic Functions:
 pow(): Raises a number to a specified power.
power_result = pow(2, 3) # Result is 8
 math.exp(): Computes the exponential of a number.
import math
exponential_result = math.exp(1) # Result is approximately 2.71828
 math.log(): Computes the natural logarithm of a number.
import math
logarithm_result = math.log(10) # Result is approximately 2.30259

Topic – Related modules


In Python, related modules are external libraries or packages that provide
additional functionality or capabilities related to a specific domain or task.
These modules extend Python's built-in functionality by offering pre-defined
functions, classes, and constants that can be imported and used in your
programs.
Math Module (math):
 Provides a wide range of mathematical functions and constants.
 Includes functions for trigonometry, exponentiation, logarithms, and
more.
 Allows you to work with complex numbers.
Example: import math
Random Module (random):
 Offers functions for generating random numbers and making random
selections.
 Useful for simulations, games, and any application that requires
randomness.
Example: import random
Datetime Module (datetime):
 Provides classes and functions for working with dates and times.
 Allows you to create, format, and manipulate date and time objects.
Example: import datetime
Pandas Module (pandas):
 Provides data structures and functions for data manipulation and
analysis.
 Allows you to work with tabular data efficiently.
Example: import pandas as pd
NumPy Module (numpy):
 A library for numerical computing in Python.
 Provides arrays and functions for performing mathematical and statistical
operations on large datasets.
Example: import numpy as np

Topic – Object, class, method creation, method calling


objects, classes, methods, and method calling are fundamental concepts of
object-oriented programming (OOP)
Object:
 An object is an instance of a class. It is a self-contained unit that
combines both data (attributes) and behaviour (methods).
 Objects are created from classes and represent real-world entities or
concepts in your program.
Class:
 A class is a blueprint or template for creating objects. It defines the
structure and behaviour that objects of the class will have.
 A class encapsulates attributes (variables) and methods (functions) that
operate on those attributes.
 Classes are defined using the class keyword.
 Example of a simple class definition:
class Dog:
def init (self, name, breed):
self.name = name
self.breed = breed

def bark(self):
return f"{self.name} barks loudly!"
Method Creation:
 Methods are functions defined within a class that perform operations
on the class's attributes or provide functionality related to the class.
 The def keyword is used to create methods within a class.
 The first parameter of a method is always self, which represents the
instance of the class on which the method is called.
 You can define methods to access and modify attributes or perform
other tasks specific to the class.
 In the example above, the Dog class has a constructor method init
and a method bark.
Method Calling:
 To call a method on an object, you use the dot notation, specifying the
object followed by the method name and parentheses.
 The self parameter is implicitly passed when you call a method on an
object. You don't need to provide it explicitly.
 Example of creating an object and calling its methods:
# Creating a Dog object
my_dog = Dog("Buddy", "Golden Retriever")
# Calling methods on the Dog object
print(my_dog.bark()) # Output: "Buddy barks loudly!"

Topic: (Sequences) – Strings, Lists, Tuples, Mapping and


Set types
Sequence is an ordered collection of items or elements. Sequences are one of
the fundamental data types in Python, and they allow you to store and
manipulate multiple values. The three main types of sequences in Python are:
Strings:
 Strings are sequences of characters enclosed in either single (') or double
(") quotes.
 They are immutable, so you cannot change individual characters within a
string.
 Example:
# Creating a string
greeting = "Hello, world!"
# Accessing characters
first_char = greeting[0]
last_char = greeting[-1]
# Slicing the string
substring = greeting[7:12]
# Concatenating strings
new_greeting = greeting + " Have a nice day!"
# Iterating through the string
for char in greeting:
print(char)
Lists:
 Lists are ordered collections of items enclosed in square brackets [ ].
 They are mutable, which means you can change their contents by
adding, removing, or modifying elements.
 Lists can contain elements of different data types.
 Example:
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# Adding an element to the list
numbers.append(6)
# Modifying an element
numbers[0] = 0
# Removing an element
numbers.remove(3)
# Iterating through the list
for number in numbers:
print(number)

Tuples:
 Tuples are similar to lists, but they are enclosed in parentheses ( ).
 They are immutable, meaning their elements cannot be changed after
creation.
 Tuples can also contain elements of different data types.
 Example:
# Creating a tuple of colors
colors = ('red', 'green', 'blue')
# Accessing elements
first_color = colors[0]
second_color = colors[1]
# Iterating through the tuple
for color in colors:
print(color)
Mapping Types:
Mapping types in Python are collections of key-value pairs. In other words, they
allow you to associate values (the "values") with unique keys (the "keys").
The keys are used to retrieve the corresponding values. Python provides a
built-in mapping type called a dictionary.
Dictionary (dict):
 A dictionary is an unordered collection of key-value pairs enclosed in
curly braces {} or created using the dict() constructor.
 Keys within a dictionary are unique, immutable (e.g., strings, numbers,
or tuples), and used to access the associated values.
 Dictionaries are often used when you need to store and retrieve data
based on specific identifiers or labels.
Example:
# Creating a dictionary
student = {
"name": "Alice",
"age": 25,
"grade": "A"
}
# Accessing values using keys
print(student["name"]) # Output: "Alice"

Set Types:
Set types in Python are collections of unique, unordered elements. Sets are
similar to lists or tuples, but they do not allow duplicate values.
Set (set):
 A set is an unordered collection of unique elements enclosed in curly
braces {} or created using the set() constructor.
 Sets are commonly used for tasks that involve testing membership or
removing duplicates from a collection.
Example:
# Creating a set
fruits = {"apple", "banana", "cherry"}
# Adding an element to the set
fruits.add("orange")

# Removing an element from the set


fruits.remove("banana")

# Checking membership
print("apple" in fruits) # Output: True

Frozen Set (frozenset):


 A frozenset is an immutable version of a set, meaning once you create a
frozenset, you cannot change its elements.
 Frozensets are often used as keys in dictionaries due to their
immutability.
Example:
# Creating a frozenset
vowels = frozenset({"a", "e", "i", "o", "u"})

# Attempting to add an element (results in an error)


# vowels.add("y") # Raises an error

You might also like