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

Unit 2

Uploaded by

Manik Rajput
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)
64 views11 pages

Unit 2

Uploaded by

Manik Rajput
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/ 11

UNIT-2 Python Data Types

Understanding Python Variables

In Python, variables are used to store data values. They act as labels or references to memory
locations where data is stored. Here are some key points to understand about Python
variables:
Dynamic Typing: Unlike some other programming languages, Python is dynamically typed,
meaning you don't have to declare the type of a variable before assigning a value to it. Python
infers the type based on the value assigned.
x = 5 # x is an integer
y = "Hello" # y is a string

Variable Naming Rules:


Variable names must start with a letter (a-z, A-Z) or an underscore (_).
They can contain letters, numbers, and underscores.
Variable names are case-sensitive (myVar and myvar are different variables).

Assignment: Assigning a value to a variable is done using the assignment operator (=).
age = 25
name = "John"

Multiple Assignments: You can assign multiple values to multiple variables in a single line.
a, b, c = 5, 10, 15

Reassignment: Variables can be reassigned to new values.


x=5
x = x + 1 # x now holds the value 6

Data Types: Variables can hold values of different data types such as integers, floats, strings,
lists, tuples, dictionaries, etc.
age = 25 # Integer
height = 5.9 # Float
name = "John" # String

Immutable vs. Mutable: Some data types like integers, floats, strings, and tuples are
immutable, meaning their values cannot be changed after they are created. Other types like
lists and dictionaries are mutable, meaning their values can be modified after creation.
my_string = "Hello"
my_string = "Hi" # Valid, as it's reassigning the variable

my_list = [1, 2, 3]
my_list.append(4) # Valid, as it's modifying the list
Scope: Variables have a scope that defines where they can be accessed. Variables declared
inside a function are local to that function, while variables declared outside of any function
are global.
global_var = 10 # Global variable

def my_function():
local_var = 5 # Local variable
print(global_var) # Can access global variable

print(local_var) # Error, local_var is not defined outside the function

Understanding python blocks


In Python, blocks of code are defined by their indentation level. Unlike many other
programming languages that use curly braces or keywords to denote the beginning and end of
blocks, Python relies on indentation to define the scope of code blocks. This indentation is
typically done using spaces or tabs, but it must be consistent throughout your code.

Here's a brief overview of how blocks work in Python:


Indentation: Blocks of code are defined by their level of indentation. Each level of indentation
represents a different block.
Colon (:): In Python, a colon (:) is used to indicate the beginning of a new block. Typically, it
comes at the end of a statement that introduces a new block, such as if, else, elif, for, while,
def, class, etc.
Consistency: Indentation must be consistent within each block of code. That means you can't
mix tabs and spaces for indentation within the same block.

Here's an example to illustrate these concepts:


if True:
print("This is the first block")
if False:
print("This is a nested block")
else:
print("This is still part of the first block")
print("This is also part of the first block")
print("This is outside of the first block")

In this example:
The first print statement, along with the nested if and else blocks and their corresponding print
statements, are all part of the outer if block.
The last print statement is not indented, so it's outside of the outer if block.
Correct indentation is crucial for Python code to function as expected. It helps maintain clarity
and readability in your code. If you're using a text editor or IDE, it often helps automatically
manage indentation for you.
Python Data Types
Python supports various data types that are used to store different kinds of values. Some of
the commonly used data types in Python include:

Integer (int): Integers are whole numbers without any decimal point. They can be positive,
negative, or zero. For example:
x=5
y = -10

Float (float): Floats are numbers with a decimal point or numbers written in exponential
form. For example:
pi = 3.14
radius = 2.5

String (str): Strings are sequences of characters enclosed within single, double, or triple
quotes. For example:
name = 'Riya Kukreti'
message = "Hello, World!"

Boolean (bool): Boolean data type represents truth values, True or False. For example:
is_valid = True
is_complete = False

List: Lists are ordered collections of items, which can be of different data types. They are
mutable, meaning their elements can be changed after creation. For example:
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']

Tuples: Tuples are similar to lists but are immutable, meaning their elements cannot be
changed after creation. They are defined using parentheses. For example:

coordinates = (10, 20)


colors = ('red', 'green', 'blue')

Dictionary (dict): Dictionaries are ordered collections of key-value pairs. Each key-value
pair maps the key to its corresponding value. For example:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

Set: Sets are unordered collections of unique elements. They are defined using curly braces
{}. For example:
unique_numbers = {1, 2, 3, 4, 5}
vowels = {'a', 'e', 'i', 'o', 'u'}

Mutable and Immutable Data types concept in python


In Python, data types can be classified into two categories based on their mutability:

Mutable Data Types:


Mutable data types are those whose values can be changed after they are created.
Changes to mutable objects happen in-place, meaning the object itself is modified.
Examples of mutable data types in Python include lists, dictionaries, and sets.

Example of mutable data types:


# Mutable data types
my_list = [1, 2, 3, 4, 5]
my_list[0] = 10 # Modifying the first element of the list
print(my_list) # Output: [10, 2, 3, 4, 5]

my_dict = {'a': 1, 'b': 2, 'c': 3}


my_dict['a'] = 100 # Modifying the value associated with the key 'a'
print(my_dict) # Output: {'a': 100, 'b': 2, 'c': 3}

Immutable Data Types:


Immutable data types are those whose values cannot be changed after they are created.
Once created, the value of an immutable object cannot be modified.
Operations that appear to modify immutable objects actually create new objects with the
updated value.
Examples of immutable data types in Python include integers, floats, strings, tuples, and
frozensets.

Example of immutable data types:


# Immutable data types
my_tuple = (1, 2, 3)
# Attempting to modify a tuple will result in an error
# my_tuple[0] = 10 # TypeError: 'tuple' object does not support item assignment

my_str = "hello"
# Attempting to modify a string will result in an error
# my_str[0] = 'H' # TypeError: 'str' object does not support item assignment

String manipulations: subscript operator, Indexing, Slicing a string


String manipulation involves various operations performed on strings, such as accessing
individual characters, slicing, modifying, and concatenating strings. The subscript operator,
indexing, and slicing are fundamental techniques for working with strings in many
programming languages like Python. Here's a brief overview of each:

Subscript Operator ([]):


In many programming languages, including Python, the subscript operator ([]) is used to access
individual characters within a string.
Characters in a string are indexed starting from 0, with the first character at index 0, the second
at index 1, and so on.
For example, in Python:
my_string = "Hello"
print(my_string[0]) # Output: 'H'
print(my_string[1]) # Output: 'e'
Indexing([]):
In Python, string indexing refers to accessing individual characters or substrings within a string
by using their positions or indices. String indexing in Python starts from 0, meaning the first
character of a string is at index 0, the second character is at index 1, and so on.
Here's how string indexing works in Python:
1.Accessing Individual Characters:
You can access individual characters in a string by using square brackets ([]) with the index of
the character you want to access.
Example:
my_string = "Hello"
print(my_string[0]) # Output: 'H'
print(my_string[1]) # Output: 'e'
print(my_string[2]) # Output: 'l'

2.Negative Indexing:
Python also supports negative indexing, where -1 refers to the last character, -2 refers to the
second last character, and so on.
Example:
my_string = "Hello"
print(my_string[-1]) # Output: 'o'
print(my_string[-2]) # Output: 'l'

Slicing:
Slicing is a technique used to extract a substring from a string by specifying a range of indices.
It follows the syntax [start:stop:step], where start is the starting index (inclusive), stop is the
stopping index (exclusive), and step is the step size (default is 1).
If start is omitted, slicing starts from the beginning of the string; if stop is omitted, slicing goes
to the end of the string.
Slicing returns a new string containing the characters from the specified range.
Example:
my_string = "Hello, World!"
print(my_string[0:5]) # Output: 'Hello'
print(my_string[7:12]) # Output: 'World'
print(my_string[:5]) # Output: 'Hello'
print(my_string[7:]) # Output: 'World!'

Defining list and list slicing in python


In Python, a list is a data structure that stores a collection of items, which can be of different
data types such as integers, floats, strings, or even other lists. Lists are mutable, which means
that you can modify their elements after they have been created. Lists are defined using
square brackets [] and the elements are separated by commas.
Here's how you define a list:

my_list = [1, 2, 3, 4, 5]

List slicing is a technique used to extract a subset of elements from a list. It allows you to
create a new list containing a portion of the elements from the original list. The syntax for list
slicing is list[start:stop:step],
where:
start is the index of the first element you want to include in the slice (inclusive).
stop is the index of the first element you do not want to include in the slice (exclusive).
step is the increment between each index in the slice (default is 1).

Here are some examples of list slicing:


my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Get elements from index 2 to 5 (exclusive)


slice1 = my_list[2:5]
print(slice1) # Output: [3, 4, 5]

# Get elements from index 0 to 7 (exclusive) with step 2


slice2 = my_list[0:7:2]
print(slice2) # Output: [1, 3, 5, 7]

# Get elements from index 3 to the end of the list


slice3 = my_list[3:]
print(slice3) # Output: [4, 5, 6, 7, 8, 9, 10]

# Get elements from the beginning of the list to index 5 (exclusive)


slice4 = my_list[:5]
print(slice4) # Output: [1, 2, 3, 4, 5]

# Get all elements in reverse order


slice5 = my_list[::-1]
print(slice5) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

EXAMPLE:
# Define a list
my_list = [1, 2, 3, 4, 5]

# Print the original list


print("Original list:", my_list)

# Append an element to the end of the list


my_list.append(6)
print("List after appending 6:", my_list)

# Insert an element at a specific position


my_list.insert(2, 10)
print("List after inserting 10 at index 2:", my_list)

# Remove an element from the list


my_list.remove(3)
print("List after removing 3:", my_list)

# Pop an element from a specific position


popped_element = my_list.pop(4)
print("Popped element:", popped_element)
print("List after popping element at index 4:", my_list)

# Access elements using index


print("Element at index 1:", my_list[1])
# Change the value of an element
my_list[0] = 100
print("List after changing value at index 0 to 100:", my_list)

# Slice the list


sliced_list = my_list[2:5]
print("Sliced list:", sliced_list)

# Iterate over the list


print("Iterating over the list:")
for element in my_list:
print(element)

# Check if an element is in the list


print("Is 10 in the list?", 10 in my_list)

# Find the length of the list


print("Length of the list:", len(my_list))

# Sort the list


my_list.sort()
print("Sorted list:", my_list)

# Reverse the list


my_list.reverse()
print("Reversed list:", my_list)

Declaring and using numeric data types:int, float, and complex using string
data type and string operations
To declare and use numeric data types (int, float, and complex) using string data types and
string operations in Python, you can create strings that represent numeric values and then
convert them to the desired numeric data type using type casting.
# Declare string variables representing numeric values
int_str = "10"
float_str = "3.14"
complex_str = "2+3j"

# Convert string variables to numeric data types


int_num = int(int_str)
float_num = float(float_str)
complex_num = complex(complex_str)

# Perform operations on numeric data types


result_sum = int_num + float_num
result_product = complex_num * float_num

# Display results
print("Integer:", int_num)
print("Float:", float_num)
print("Complex:", complex_num)
print("Sum of integer and float:", result_sum)
print("Product of complex and float:", result_product)
Output:
Integer: 10
Float: 3.14
Complex: (2+3j)
Sum of integer and float: 13.14
Product of complex and float: (9.42+6.28j)

In this example, we first declare string variables int_str, float_str, and complex_str,
representing integer, float, and complex values, respectively. Then, we use the int(), float(),
and complex() functions to convert these strings into their corresponding numeric data types.
After converting the strings to numeric data types, we perform operations on these variables
and display the results.

Tuple in Python
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar
to a Python list in terms of indexing, nested objects, and repetition but the main difference
between both is Python tuple is immutable, unlike the Python list which is mutable.

Creating Python Tuples


There are various ways by which you can create a tuple in Python. They are as follows:
• Using round brackets
• With one item
• Tuple Constructor

Create Tuples using Round Brackets ()


To create a tuple we will use () operators.
var = ("Riya", "Kukreti")
print(var)

Create a Tuple With One Item


values : tuple[int | str, ...] = (1,2,4,"Riya")
print(values)

Tuple Constructor in Python


tuple_constructor = tuple(("dsa", "developement", "deep learning"))
print(tuple_constructor)

Here's a basic example of creating tuples:


# Creating tuples
tuple1 = (1, 2, 3, 4, 5)
tuple2 = ('apple', 'banana', 'orange')
tuple3 = (1, 'hello', 3.14, True)

# Accessing elements of a tuple


print(tuple1[0]) # Output: 1
print(tuple2[1]) # Output: banana
print(tuple3[2]) # Output: 3.14

Tuples support various operations such as indexing, slicing, and concatenation, just like lists.
However, you cannot modify the elements of a tuple after it has been created.

# Tuple slicing
tuple4 = (1, 2, 3, 4, 5)
print(tuple4[1:4]) # Output: (2, 3, 4)

# Concatenating tuples
tuple5 = tuple1 + tuple2
print(tuple5) # Output: (1, 2, 3, 4, 5, 'apple', 'banana', 'orange')

Attempting to modify a tuple will result in a TypeError:


tuple1[0] = 10 # TypeError: 'tuple' object does not support item assignment

Tuples are commonly used in Python for various purposes:


Returning Multiple Values from Functions: Functions can return multiple values as a tuple.

def get_coordinates():
x = 10
y = 20
return x, y

coordinates = get_coordinates()
print(coordinates) # Output: (10, 20)

Efficient Packing and Unpacking: Tuples are used for efficient packing and unpacking of
data.

x, y, z = (10, 20, 30)


print(x) # Output: 10
print(y) # Output: 20
print(z) # Output: 30

Different Operations Related to Tuples


Below are the different operations related to tuples in Python:
• Concatenation
• Nesting
• Repetition
• Slicing
• Deleting
• Finding the length
• Multiple Data Types with tuples
• Conversion of lists to tuples
• Tuples in a Loop
Dictionary Keys: A dictionary in Python is a data structure that stores the value in
value:key pairs.
person = {('John', 'Doe'): 30, ('Alice', 'Smith'): 25}
print(person[('John', 'Doe')]) # Output: 30

Python Dictionary Syntax


dict_var = {key1 : value1, key2 : value2, …..}

Dictionaries in Python is a data structure, used to store values in key:value format. This
makes it different from lists, tuples, and arrays as in a dictionary each key has an associated
value.

Note: As of Python version 3.7, dictionaries are ordered and can not contain duplicate values.

How to Create a Dictionary


In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a ‘comma’.
The dictionary holds pairs of values, one being the Key and the other corresponding pair
element being its Key:value.
Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be
repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
The code demonstrates creating dictionaries with different types of keys. The first dictionary
uses integer keys, and the second dictionary uses a mix of string and integer keys with
corresponding values. This showcases the flexibility of Python dictionaries in handling
various data types as keys.

Sets:
In Python, sets and dictionaries are two distinct data types with different characteristics and
use cases:
Sets:
1. Sets are unordered collections of unique elements.
2. Sets are defined using curly braces {} or by using the set() constructor.
3. Sets do not allow duplicate elements. If you try to add duplicate elements to a set,
they are ignored.
4. Sets support mathematical set operations like union, intersection, difference, and
symmetric difference.
5. Sets are mutable, meaning you can add or remove elements after creation.
6. Elements of a set must be immutable types (e.g., integers, strings, tuples), but a set
itself is mutable.
7. Sets are often used for membership testing, eliminating duplicates, and mathematical
operations.
Example:
# Creating sets
my_set = {1, 2, 3, 4, 5}
my_set2 = set([4, 5, 6, 7, 8])
# Adding elements to a set
my_set.add(6)

# Removing elements from a set


my_set.remove(3)

# Set operations
union_set = my_set.union(my_set2)
intersection_set = my_set.intersection(my_set2)
difference_set = my_set.difference(my_set2)

Dictionaries:
1. Dictionaries are collections of key-value pairs.
2. Dictionaries are defined using curly braces {} with key-value pairs separated by
colons :.
3. Dictionaries are mutable and ordered, meaning the order of elements is not
guaranteed.
4. Keys within a dictionary must be unique and immutable (e.g., strings, numbers,
tuples).
5. Values within a dictionary can be of any data type and can be mutable.
6. Dictionaries are commonly used for mapping keys to values, such as storing
information about objects, configurations, or database records.

Example:
# Creating dictionaries
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_dict2 = dict(zip(['a', 'b', 'c'], [1, 2, 3]))

# Accessing elements in a dictionary


print(my_dict['name']) # Output: John

# Modifying elements in a dictionary


my_dict['age'] = 31

# Adding new key-value pairs to a dictionary


my_dict['gender'] = 'Male'

# Removing key-value pairs from a dictionary


del my_dict['city']

You might also like