Unit-4 Python
Unit-4 Python
DATA TYPES
What are the 4 data types in Python?
The data types in Python that we will look at in this tutorial are integers, floats,
Boolean, and strings. If you are not comfortable with using variables in Python,
our article on how to declare python variables can change that.
Python Data types are the classification or categorization of data items. It
represents the kind of value that tells what operations can be performed on a
particular data. Since everything is an object in Python programming, Python data
types are classes and variables are instances (objects) of these classes. The
following are the standard or built-in data types in Python:
Numeric – int, float, complex
Sequence Type – string, list, tuple
Mapping Type – dict
Boolean – bool
Set Type – set, frozenset
Binary Types – bytes, bytearray, memoryview
This code assigns variable ‘x’ different values of various Python data types. It
covers string , integer , float , complex , list , tuple , range , dictionary , set ,
frozenset , boolean , bytes , bytearray , memoryview , and the special
value ‘None’ successively. Each assignment replaces the previous value,
making ‘x’ take on the data type and value of the most recent assignment.
x = "Hello World"
x = 50
x = 60.5
x = 3j
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
x = range(10)
x = {"name": "Suraj", "age": 24}
x = {"geeks", "for", "geeks"}
x = frozenset({"geeks", "for", "geeks"})
x = True
x = b"Geeks"
x = bytearray(4)
x = memoryview(bytes(6))
x = None
If you’re eager to deepen your understanding of Python and how it handles
data, our Python Programming Self Paced Course is the perfect place to start.
This course covers everything from the fundamentals to more advanced topics,
giving you the hands-on experience needed to confidently work with Python in
real-world projects.
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A
numeric value can be an integer, a floating number, or even a complex number.
These values are defined as Python int , Python float , and Python
complex classes in Python .
Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to
how long an integer value can be.
Float – This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
Complex Numbers – A complex number is represented by a complex class. It
is specified as (real part) + (imaginary part)j . For example – 2+3j
Example: This code demonstrates how to determine the data type of variables
in Python using type() function. It prints the data types of three variables : a
(integer) , b (float) , and c (complex). The output shows the respective data
type Python for each variable.
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or
different Python data types. Sequences allow storing of multiple values in an
organized and efficient fashion. There are several sequence data types of
Python:
Python String
Python List
Python Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string
is a collection of one or more characters put in a single quote, double-quote, or
triple-quote. In Python, there is no character data type Python, a character is a
string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes, double quotes, or even
triple quotes.
Example: This Python code showcases various string creation methods. It uses
single quotes, double quotes, and triple quotes to create strings with different
content and includes a multiline string. The code also demonstrates printing the
strings and checking their data types.
s1 = 'Welcome to the Geeks World'
print("String with Single Quotes: ", s1)
# check data type
print(type(s1))
s2 = "I'm a Geek"
print("String with Double Quotes: ", s2)
s3 = '''I'm a Geek and I live in a world of "Geeks"'''
print("String with Triple Quotes: ", s3)
s4 = '''Geeks
For
Life'''
print("Multiline String: ", s4)
Output
String with Single Quotes: Welcome to the Geeks World
<class 'str'>
String with Double Quotes: I'm a Geek
String with Triple Quotes: I'm a Geek and I live in a world of "Geeks"
Multiline String: G...
Accessing elements of String
In Python programming , individual characters of a String can be accessed by
using the method of Indexing. Negative Indexing allows negative address
references to access characters from the back of the String, e.g. -1 refers to the
last character, -2 refers to the second last character, and so on.
Example: This Python code demonstrates how to work with a string named
‘ String1′ . It initializes the string with “GeeksForGeeks” and prints it. It then
showcases how to access the first character ( “G” ) using an index of 0 and the
last character ( “s” ) using a negative index of -1.
s = "GeeksForGeeks"
# accessing first character of string
print(s[0])
# accessing last character of string
print(s[-1])
Output
Python String
List Data Type
Lists are just like arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of the
same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square
brackets[].
Example: This Python code demonstrates list creation and manipulation. It
starts with an empty list and prints it. It creates a list containing a single string
element and prints it. It creates a list with multiple string elements and prints #
Empty list
a = []
# list with int values
a = [1, 2, 3]
print(a)
# list with mixed int and string
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)
Output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
Python Access List ItemsIn order to access the list items refer to the index
number. Use the index operator [ ] to access an item in a list. In Python,
negative sequence indexes represent positions from the end of the array. Instead
of having to compute the offset as in List[len(List)-3], it is enough to just write
List[-3]. Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second-last item, etc.
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2]
print(a[-1])
print(a[-3])
Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
4
t2 = ('Geeks', 'For')
5
print("\nTuple with the use of String: ", t2)
Output
Tuple with the use of String: ('Geeks', 'For')
A text string, also known as a string or simply as text, is a group of characters
that are used as data in a spreadsheet program. Text strings are most often
comprised of words, but may also include letters, numbers, special characters,
the dash symbol, or the number sign
A string is a sequence of characters enclosed between the double quotes "..."
Example: "abc123" "Hello World" "Hello, what is your name ?"
A text string is a sequence of characters that stores human-readable text, such as
words and sentences. In computer science, strings are used to communicate
information between a computer program and its user.
Here are some examples of text strings:
"abc123"
"Hello World"
"Hello, what is your name ?"
Here are some ways to represent text strings in different programming
languages:
Wolfram Language: The TextString function converts expressions into a
human-readable string representation.
Arduino: Text strings can be represented using the String data type or by
creating a string from an array of type char.
C#: A string is an object of type String whose value is text.
JavaScript: Strings are written with quotes, such as single or double quotes.
Excel: The TEXT function is used to combine text and numbers, such as dates,
times, or currency.
In Python, a string is a sequence of characters enclosed within single quotes (''),
double quotes ("") or triple quotes (''' ''' or """ """).
Here are a few essential things to know about strings in Python:
Creating Strings:
Python
# Using single quotes
my_string = 'Hello, World!'
# Using double quotes
my_string = "Hello, World!"
# Using triple quotes for multi-line strings
my_string = '''This is a
multi-line
string.'''
Accessing Characters:
Python
Execution output
my_string = "Hello"
print(my_string[0])
print(my_string[1])
H
String Concatenation:
Execution output
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result)
Hello World
String Methods:
Python provides a wide range of built-in methods to manipulate strings. Some
common examples:
len(): Returns the length of the string.
upper(): Converts the string to uppercase.
lower(): Converts the string to lowercase.
replace(): Replaces a substring with another.
split(): Splits the string into a list based on a delimiter.
find(): Finds the index of a substring.
startswith(): Checks ifsss a string starts with a specific substring.
endswith(): Checks if a string ends with a specific substring.
Example:
Python
Execution output
my_string = "Hello, World!"
print(len(my_string))
print(my_string.upper())
print(my_string.replace("World", "Python"))
13
HELLO, WORLD!
Hello, Python!
Immutability:
Strings in Python are immutable, meaning you cannot modify their contents
directly. Any operation that appears to modify a string actually creates a new
string.
Formatting Strings:
Python offers several ways to format strings, including: f-strings (Python 3.6
and above).
Execution output
name = "Alice"
age = 30
print(f"Hello, my name is {name} and I am {age} years old.")
Hello, my name is Alice and I am 30 years old.
.format() method.
Execution output
name = "Bob"
print("Hello, my name is {}.".format(name))
Hello, my name is Bob.
% operator (older style).
Execution output
name = "Charlie"
print("Hello, my name is %s." % name)
Hello, my name is Charlie.
Retrieving And Updating Data Contained in Shelve in Python
In Python shelve you access the keys randomly. In order to access the keys
randomly in python shelve we use open() function. This function works a lot
like the file open() function in File handling. Syntax for open the file using
Python shelve
shelve.open(filename, flag='c' , writeback=True)
In Order to access the keys randomly in shelve in Python, we have to take three
steps:
Storing Python shelve data
Retrieving Python shelve data
Updating Python shelve data
Storing Python shelve data :
In order to store python shelve data, we have to create a file with full of datasets
and open them with a open() function this function open a file which we have
created.
# At first, we have to import the 'Shelve' module.
import shelve
# In this step, we create a shelf file.
shfile = shelve.open("shelf_file")
# we create a data object which in this case is a book_list.
my_book_list =['bared_to_you', 'The_fault_in_our_stars',
'The_boy_who_never_let_her_go']
# we are assigning a dictionary key to the list
# which we will want to retrieve
shfile['book_list']= my_book_list
35
file1.seek(0)
36
# readlines function
37
print("Output of Readlines function is ")
38
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Write to Text File in Python
There are two ways to write in a file:
Using write()
Using writelines()
Reference: write() VS writelines()
Writing to a Python Text File Using write()
write(): Inserts the string str1 in a single line in the text file.
File_object.write(str1)
file = open("Employees.txt", "w")
for i in range(3):
name = input("Enter the name of the employee: ")
file.write(name)
file.write("\n")
file.close()
print("Data is written into the file.")
Output:
Data is written into the file.
Writing to a Text File Using writelines()
writelines(): For a list of string elements, each string is inserted in the text
file.Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
file1 = open("Employees.txt", "w")
lst = []
for i in range(3): name = input("Enter the name of the employee: ")
lst.append(name + '\n')
file1.writelines(lst) s
file1.close()
print("Data is written into the file.")
Output:
Structured binary files are files that store data in a binary format, which is a
series of bits that represent data:
Structure: Binary files are structured internally according to a specific file
format. They typically have a header section with metadata, followed by the
data encoded in binary.
Data types: Binary files can store a wide range of data types, including
numbers, images, databases, and more.
Reading: Binary files are not human readable and require a special program or
hardware processor to read.
Uses: Binary files are commonly used in building applications and
software. Programmers often refer to executable programs or compiled
application files as binaries.
Advantages: Binary files are permanent, always available, and can be very
large.
Disadvantages: Disk access time can be slow.
Binary Structured Data Format (BSDF) is a format that supports a variety of
data types, including integers, floats, strings, lists, and mappings. BSDF has
implementations for multiple languages
Structured binary files store data in a predefined binary format, making them
more compact and efficient than text-based files. They're widely used for
performance-critical applications, such as image storage, video encoding,
databases, and embedded systems.
Key Characteristics
Compact Representation: Data is stored in a raw binary format, minimizing
file size
Predefined Structure: The structure is determined by a schema or format
specification, ensuring consistent interpretation of the data.
Platform-Specific: Endianness (byte order) and word size can vary between
platforms, making cross-platform compatibility a challenge without
standardization.
Structure of a Binary File
Binary files are typically structured into sections, such as:
Header: Contains metadata about the file, such as version, file size, or format
specifications.
Data Blocks: Store the main data in a structured format (e.g., integers, floats,
strings).
Footer (Optional): May include checksums, end markers, or other metadata.
Use Cases
Media Files: Images (e.g., PNG, JPEG), audio (e.g., MP3, WAV), video (e.g.,
MP4).
Databases: Binary file formats for efficient storage and querying.
Networking: Protocols use binary formats for compact data transmission.
Embedded Systems: Firmware and data storage in resource-constrained
devices.
Example of a Structured Binary File
Here’s a basic example of a binary file structure for storing employee records:
Header: Includes the number of records and a version number.
Record Data:
Employee ID (4 bytes, integer)
Name (30 bytes, string, fixed length)
Age (1 byte, integer)
Salary (4 bytes, float)
Writing and Reading Binary Files (Python Example)
Copy codeimport struct
# Define the format (4s = string[4], i = integer, f = float)
record_format = "4si30sf"
# Writing a binary file
with open("employees.bin", "wb") as file:
# Header: 2 records, version 1
file.write(struct.pack("i", 2)) # Number of records
file.write(struct.pack("i", 1)) # Version
# Record 1
file.write(struct.pack(record_format, b"EMP1", 25, b"John Doe".ljust(30, b'\
0'), 55000.0))
# Record 2
file.write(struct.pack(record_format, b"EMP2", 30, b"Jane Smith".ljust(30,
b'\0'), 62000.0))# Reading a binary file
with open("employees.bin", "rb") as file:
num_records = struct.unpack("i", file.read(4))[0]
version = struct.unpack("i", file.read(4))[0]
print(f"Number of Records: {num_records}, Version: {version}")
for _ in range(num_records):
data = file.read(struct.calcsize(record_format))
emp_id, age, name, salary = struct.unpack(record_format, data)
print(f"ID: {emp_id.decode().strip()}, Age: {age}, Name:
{name.decode().strip()}, Salary: {salary}")
Key Components
1. Tables:
o Rows (Tuples): Represent individual records.
o Columns (Attributes): Represent fields of data for each record.
2. Schema:
o Defines the structure of the database, including tables, columns, data types,
and constraints.
3. Keys:
o Primary Key: A unique identifier for each record in a table.
o Foreign Key: A field that establishes a relationship between two tables.
4. Relationships:
o One-to-One: A record in one table corresponds to one record in another.
o One-to-Many: A record in one table corresponds to many records in another.
o Many-to-Many: Multiple records in one table correspond to multiple records
in another, typically managed with a junction table
Characteristics
SQL Operations
Example Schema
ables: Users and Orders
Users
Orders
1. Open Source:
o MySQL
o PostgreSQL
o MariaDB
2. Commercial:
o Oracle Database
o Microsoft SQL Server
o IBM Db2
NoSQL Data StoresNoSQL (Not Only SQL) data stores are non-relational
databases designed to handle large-scale, unstructured, or semi-structured data. Unlike
traditional relational databases, they offer flexibility in schema design, scalability, and
performance for specific use cases like big data, real-time analytics, and distributed systems
Key Characteristics
Schema Flexibility: NoSQL databases often allow schema-less or dynamic schemas, making
them adaptable to changes in data structure.
Horizontal Scalability: Built to scale across multiple nodes, enabling handling of large
volumes of data and high throughput.
Varied Data Models: Support for diverse data models tailored to specific application
needs.Eventual Consistency: Some NoSQL databases prioritize availability and partition
tolerance (CAP theorem) over strict consistency
Types of NoSQL Databases
1. Document Stores:
o Store data as JSON, BSON, or XML documents.
o Schema-free, allowing flexible data structures.
o Example Use Case: Content management systems, catalogs.
o Examples: MongoDB, Couchbase, RavenDB.
2. Key-Value Stores:
o Store data as key-value pairs.
o Simple structure, highly performant for quick lookups.
o Example Use Case: Caching, session storage.
o Examples: Redis, DynamoDB, Riak.
3. Column-Family Stores:
o Organize data into rows and columns, but allow variable column structures.
o Designed for large-scale distributed storage and analytics.
o Example Use Case: Time-series data, logs.
o Examples: Cassandra, HBase.
4. Graph Databases:
o Use nodes, edges, and properties to represent and store relationships.
o Optimize for complex relationship queries.
o Example Use Case: Social networks, recommendation systems.
o Examples: Neo4j, Amazon Neptune.
5. Time-Series Databases:
o Specialized for time-stamped or sequentially ordered data.
o Example Use Case: Monitoring systems, IoT data.
o Examples: InfluxDB, TimescaleDB
Sample Document:
json
Copy code
{
"userId": 1,
"name": "Alice Smith",
"email": "[email protected]",
"orders": [
{"orderId": 101, "product": "Laptop", "quantity": 1},
{"orderId": 102, "product": "Smartphone", "quantity": 2}
}
javascript
Copy code
// Find user with a specific email
db.users.find({ email: "[email protected]" });
// Insert a new user
db.users.insertOne({
userId: 2,
name: "Bob Johnson",
email: "[email protected]",
orders: []
});
// Update a user's orders
db.users.updateOne(
{ userId: 1 },
{ $push: { orders: { orderId: 103, product: "Tablet", quantity: 1 } } }
);
Advantages of NoSQL
Challenges
Consistency: May trade strict consistency for availability and performance.
1. Complexity: Requires understanding of the underlying data model for optimal design.
2. Lack of Standardization: No unified query language like SQL, leading to steep
learning curves.
Popular NoSQL Databases
Document Stores: MongoDB, Couchbase.