[go: up one dir, main page]

0% found this document useful (0 votes)
7 views11 pages

Pyhton Unit - 1

Python is an object-oriented programming language where everything is treated as an object, allowing for encapsulation, reusability, and abstraction. It has standard data types including numeric, sequence, mapping, set, boolean, and binary types, each serving specific purposes in data storage and manipulation. Built-in functions and operators enhance the efficiency of these types, making Python versatile for various programming tasks.

Uploaded by

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

Pyhton Unit - 1

Python is an object-oriented programming language where everything is treated as an object, allowing for encapsulation, reusability, and abstraction. It has standard data types including numeric, sequence, mapping, set, boolean, and binary types, each serving specific purposes in data storage and manipulation. Built-in functions and operators enhance the efficiency of these types, making Python versatile for various programming tasks.

Uploaded by

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

1. What are Python objects?

Explain with

examples. Definition:
Python is an object-oriented programming language, meaning everything in Python is treated as an
object. An object is an instance of a class, containing attributes (data) and methods (functions).
Objects allow structured programming by encapsulating related data and behavior in one place.

In Python, even basic types like int, float, list, and dict are objects. Python’s dynamic typing means
that when a variable is assigned a value, it automatically becomes an object of a corresponding type.
Objects make Python flexible, reusable, and easy to manage.

Use:
Objects are useful because they allow:

 Encapsulation – Data and methods are kept together.

 Reusability – Once a class is created, multiple objects can be made from it.

 Abstraction – Hides unnecessary details.

 Inheritance & Polymorphism – Allows modification and extension of existing functionalities.

Example:

python

CopyEdit

class Car:

def init (self, brand, model):

self.brand = brand

self.model = model

def show(self):

print(f"{self.brand} {self.model}")

c = Car("Toyota", "Camry")

c.show() # Toyota Camry

Theory:
In the example, Car is a class, and c is an object. The init method initializes attributes, and
show() is a method that prints the values. Python automatically manages object creation and
deletion using garbage collection. Objects simplify program structure, making code more
readable and maintainable.
2. Explain Python’s standard data types with

examples. Definition:
Python provides standard data types to store and manipulate data. These types determine how
values are stored, accessed, and modified.

Types of Standard Data Types:

1. Numeric Types: int, float, complex (Used for mathematical operations)

2. Sequence Types: str, list, tuple (Used to store ordered data)

3. Mapping Type: dict (Used for key-value storage)

4. Set Types: set, frozenset (Stores unique, unordered data)

5. Boolean Type: bool (Stores True or False)

6. Binary Types: bytes, bytearray, memoryview (For binary data handling)

Python’s dynamic typing means that variables do not need explicit declaration; they take the type of
the value assigned.

Use:

 Numeric types are used in calculations.

 Sequences store multiple values (like words or lists of numbers).

 Dictionaries are useful for key-value pair storage.

 Sets help remove duplicates and perform mathematical set operations.

Example:

python

CopyEdit

x = 10 # int

y = 3.14 # float

s = "Hello" # str

l = [1, 2, 3] # list

d = {"name": "John"} # dict

Theory:
Standard types make Python versatile and powerful. For example, list is mutable (can be changed),
whereas tuple is immutable (fixed). dict allows fast lookups using keys. set avoids duplicates,
making it useful in scenarios like removing redundant data. Understanding data types helps write
efficient and optimized Python programs.
3. What are Python’s built-in types? Explain with

examples. Definition:
Python provides several built-in types to handle different kinds of data efficiently. These types allow
developers to store, manipulate, and process information effectively. Python categorizes built-in
types into numeric types, sequence types, mapping types, set types, boolean types, and binary
types.

Categories of Built-in Types:

1. Numeric Types – int, float, complex

2. Sequence Types – str, list, tuple, range

3. Mapping Type – dict

4. Set Types – set, frozenset

5. Boolean Type – bool (True or False)

6. Binary Types – bytes, bytearray, memoryview

Python is dynamically typed, meaning variables do not need explicit type declarations; they take the
type of the assigned value.

Use:

 Numeric types help in mathematical operations.

 Sequences store ordered collections of items (like text or numbers).

 Dictionaries store data in key-value pairs, making retrieval fast.

 Sets hold unique values and allow mathematical operations.

 Boolean values are used in conditions.

 Binary types deal with low-level memory and files.

Example:

python

CopyEdit

a = 10 # int

b = 3.14 # float

c = "Python" # str

d = {"name": "Alice"} # dict

Theory:
Python’s built-in types improve efficiency and flexibility. list and tuple store collections, with lists
being mutable and tuples immutable. dict allows quick key-based lookups. set removes duplicates
and supports operations like union and intersection. Understanding these types is essential for
writing optimized and readable Python programs.

4. What are standard type operators in Python? Explain with

examples. Definition:
Operators are symbols used to perform operations on values and variables. Python provides
standard type operators for different data types, allowing manipulation of numbers, sequences,
and logical expressions.

Categories of Operators:

1. Arithmetic Operators (+, -, *, /, //, %, **) – Perform mathematical operations.

2. Comparison Operators (==, !=, >, <, >=, <=) – Compare values and return True or False.

3. Logical Operators (and, or, not) – Perform boolean logic.

4. Bitwise Operators (&, |, ^, ~, <<, >>) – Work on binary representations of numbers.

5. Membership Operators (in, not in) – Check for the presence of values in sequences.

6. Identity Operators (is, is not) – Compare object identity.

Use:

 Arithmetic operators are used for calculations.

 Comparison operators help in decision-making.

 Logical operators evaluate conditions in if statements.

 Bitwise operators manipulate bits for low-level programming.

 Membership operators check whether a value exists in a sequence.

Example:

python

CopyEdit

a=5

b = 10

print(a + b) # Arithmetic: 15

print(a < b) # Comparison: True

print(a and b) # Logical: 10

Theory:
Operators make Python powerful and expressive. Arithmetic and logical operations are
fundamental in computations and control flow. Understanding them helps in building efficient
programs with minimal code.
5. Explain built-in functions for standard types in

Python. Definition:
Built-in functions are predefined functions that perform common operations on standard data
types. They simplify tasks, eliminating the need for additional code.

Common Built-in Functions:

1. Numeric Functions: abs(), round(), pow(), max(), min(), sum()

2. String Functions: len(), str(), ord(), chr(), split(), replace()

3. List & Tuple Functions: len(), sorted(), list(), tuple(), index()

4. Dictionary Functions: dict.keys(), dict.values(), dict.items()

5. Set Functions: set.add(), set.remove(), set.union(), set.intersection()

Use:

 abs(-5) returns 5, making it useful for absolute values.

 len("hello") returns 5, counting characters in a string.

 sorted([3, 1, 2]) returns [1, 2, 3], sorting a list.

 dict.keys() returns all keys in a dictionary.

Example:

python

CopyEdit

numbers = [4, 2, 8, 1]

print(len(numbers)) # 4

print(max(numbers)) # 8

print(sorted(numbers)) # [1, 2, 4, 8]

Theory:
Built-in functions enhance productivity by handling common operations efficiently. They help in
mathematical calculations, string manipulations, and data structure operations. Understanding
them improves coding speed and efficiency.

6. How are standard types categorized in Python? Explain with

examples. Definition:
Python categorizes standard types based on how they store and manipulate data. These categories
help in choosing the right type for a particular operation. The main categories are:
1. Numeric Types: int, float, complex – Store numerical values.

2. Sequence Types: str, list, tuple, range – Store ordered collections.

3. Mapping Type: dict – Stores key-value pairs.

4. Set Types: set, frozenset – Store unordered, unique elements.

5. Boolean Type: bool – Represents True or False.

6. Binary Types: bytes, bytearray, memoryview – Handle binary data.

Use:

 Numeric types are used in calculations and scientific computing.

 Sequence types help in storing and processing text, lists, and tuples.

 Dictionaries allow fast key-based lookups, useful for large datasets.

 Sets remove duplicate values and allow set operations like union and intersection.

 Boolean values control program flow using conditional statements.

Example:

python

CopyEdit

num = 42 # int

text = "Hello" # str

items = [1, 2, 3] # list

data = {"name": "Alice"} # dict

unique = {1, 2, 3} # set

Theory:
Understanding type categorization helps in optimizing memory and performance. Choosing the right
type ensures faster computations and efficient data handling. Python’s dynamic typing allows
changing types at runtime, making programming flexible.

7. What are unsupported types in Python? Why do they

exist? Definition:
Unsupported types refer to data types that are not directly available in Python. These are types
found in lower-level languages like C or Java but are absent in Python due to its high-level
nature. Examples include:

1. Pointers – Used in C for direct memory access, but Python manages memory automatically.

2. Character Type (char) – Python uses str instead.

3. Explicit long Integer Type – Python’s int supports arbitrary precision.


4. Static Arrays – Python uses dynamic list.

5. Enums – Introduced in Python 3.4 but not a primitive type.

6. Structures (struct) – Python uses dictionaries and classes instead.

Use:

 Python removes complexities like manual memory allocation (pointers).

 Instead of a char type, Python treats strings as immutable sequences of characters.

 Python’s int supports large numbers, making long unnecessary.

 Instead of static arrays, Python’s list is

dynamic. Example:

python CopyEdit

# No need for 'char' type, use a string instead char_value =

'A'

Theory:
Python focuses on simplicity and readability, removing unnecessary low-level types. Unsupported types
are either replaced with more flexible alternatives or handled automatically by Python’s
interpreter.

8. Explain Python’s numeric types with

examples. Definition:
Python supports three numeric types:

1. Integer (int) – Whole numbers without decimals.

2. Floating-Point (float) – Numbers with decimals.

3. Complex (complex) – Numbers with a real and imaginary part.

Use:

 Integers are used for counting and indexing.

 Floats are used in scientific and financial applications.

 Complex numbers are used in mathematical computations.

Example: python

CopyEdit

x = 10 # int
y = 3.14 # float

z = 2 + 3j # complex

Theory:
Python automatically assigns the correct type based on value. Integers can be arbitrarily large
without overflow. Floating-point numbers follow IEEE 754 standards. Complex numbers help in
engineering and physics. Understanding numeric types helps in choosing the right format for
calculations.

9. Explain Python’s sequence types: Strings, Lists, and

Tuples. Definition:
Sequence types store ordered collections of elements. The three main sequence types in Python
are:

1. String (str) – A collection of characters.

2. List (list) – A mutable ordered collection.

3. Tuple (tuple) – An immutable ordered collection.

Use:

 Strings are used for text processing.

 Lists store multiple values dynamically.

 Tuples ensure data integrity when immutability is required.

Example:

python

CopyEdit

s = "Hello" # str

l = [1, 2, 3] # list

t = (1, 2, 3) # tuple

Theory:

 Strings are immutable, meaning they cannot be changed after creation.

 Lists are dynamic, allowing modifications like addition and removal of elements.

 Tuples preserve data structure, making them faster than lists.

Choosing the right sequence type ensures better performance and memory management.

10. Explain Mapping and Set types in Python with examples.


Definition:
Python provides mapping and set types to store and manage data efficiently.

1. Mapping Type (dict) – Stores key-value pairs, ensuring fast lookup.

2. Set Types (set, frozenset) – Store unique, unordered elements.

Use:

 Dictionaries allow quick access using keys.

 Sets eliminate duplicates and support mathematical

operations. Example:

python

CopyEdit

# Dictionary

d = {"name": "John", "age": 25}

# Set

s = {1, 2, 3, 4}

Theory:
Dictionaries are efficient for searching, while sets help in data validation and filtering.
Understanding these structures improves data management and program efficiency.

Buffer Question 1: Explain the significance of Python’s built-in types and their operations.

Definition:
Python has several built-in types that store and manipulate data efficiently. These include numeric
types (int, float, complex), sequence types (str, list, tuple), mapping types (dict), set types (set,
frozenset), boolean type (bool), and binary types (bytes, bytearray, memoryview).

Importance of Built-in Types:

1. Optimized Performance – Built-in types are implemented in C, making them efficient.

2. Flexibility – Python’s types are dynamically assigned, reducing complexity.

3. Rich Operations – Python provides operators and built-in functions to work with these
types easily.

Common Type Operations:

 Arithmetic (+, -, *, /, //, %, **) – Used for mathematical calculations.

 Comparison (==, !=, >, <) – Helps in decision-making.


 Membership (in, not in) – Checks for the presence of an item.

 Logical (and, or, not) – Used in conditional expressions.

Example:

python CopyEdit

x = [1, 2, 3] # List

x. append(4) # Adds 4 to the list

print(x) # [1, 2, 3, 4]

Theory:
Understanding Python’s built-in types is essential for efficient coding. The ability to perform operations
directly on these types simplifies programming, reduces development time, and makes Python code
more readable and maintainable.

Buffer Question 2: Explain Python’s number system and the operations available for numbers.

Definition:
Python supports three numeric types:

1. Integers (int) – Whole numbers (positive or negative).

2. Floating-point (float) – Numbers with decimals.

3. Complex Numbers (complex) – Numbers with a real and imaginary part.

Number System in Python:


Python supports different number bases:

 Decimal (10) – Default number system.

 Binary (0b) – Prefix 0b for binary numbers.

 Octal (0o) – Prefix 0o for octal numbers.

 Hexadecimal (0x) – Prefix 0x for hexadecimal numbers.

Mathematical Operations:

 Basic Arithmetic: +, -, *, /, //, %, **

 Comparison: ==, !=, >, <, >=, <=

 Bitwise Operations: &, |, ^, <<, >>

Example: python

CopyEdit

x = 10 # Integer
y = 3.5 # Float

z = 2 + 3j # Complex

print(x + y) # 13.5

print(bin(10)) # Binary representation: 0b1010

Theory:
Numbers are fundamental in programming, used for calculations, data representation, and scientific
computing. Python provides built-in functions like abs(), pow(), round(), and math module
functions to work with numbers efficiently. Understanding Python’s number system allows better
handling of calculations and data representation.

You might also like