Unit 2
Unit 2
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
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
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
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:
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'}
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
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!'
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).
EXAMPLE:
# Define a list
my_list = [1, 2, 3, 4, 5]
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"
# 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.
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')
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.
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.
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)
# 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]))