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

Python

The document provides an overview of Python data types, including numeric, sequence, text, mapping, set, boolean, binary, and none types, along with type conversion methods. It also explains key concepts about variables in Python, such as assignment, dynamic typing, variable naming rules, scope, mutability, and type checking. Additionally, it highlights the ability to rebind and delete variables using the del keyword.

Uploaded by

krishna M
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)
5 views

Python

The document provides an overview of Python data types, including numeric, sequence, text, mapping, set, boolean, binary, and none types, along with type conversion methods. It also explains key concepts about variables in Python, such as assignment, dynamic typing, variable naming rules, scope, mutability, and type checking. Additionally, it highlights the ability to rebind and delete variables using the del keyword.

Uploaded by

krishna M
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/ 7

Introduction:

In Python, data types define the type of value that a variable holds. These data
types are essential because they help Python interpret what kind of operations can
be performed on a particular variable and how it is stored in memory.

Here's a detailed explanation of the different data types in Python:

1. Numeric Types

These represent numbers and are the most basic types in Python.

 int (Integer): Represents whole numbers without a fractional part. For


example:

x = 5 # integer
y = -10 # negative integer

 float (Floating Point): Represents numbers with decimal points. For example:

x = 5.5 # float
y = -10.2 # negative float
z = 0.0 # float

 complex: Represents complex numbers in the form a + bj, where a is the


real part and b is the imaginary part. For example:

x = 3 + 4j # complex number
y = 1 - 2j # complex number

2. Sequence Types

These are used to store collections of values.

 list: Ordered, mutable (changeable) collection of items. Lists can contain


elements of different types, such as integers, strings, or other lists.

lst = [1, 2, 3, 'hello', [4, 5]]

 tuple: Ordered, immutable (unchangeable) collection of items. Like lists, but


once defined, they cannot be modified.

tpl = (1, 2, 3, 'hello')

 range: Represents an immutable sequence of numbers, often used in loops.


It is typically used for generating sequences of numbers, such as in a for loop.

r = range(5) # generates numbers 0, 1, 2, 3, 4


3. Text Type

This type is used to store textual data.

 str (String): Represents a sequence of characters, enclosed in either single,


double, or triple quotes.

s = "Hello, World!" # string with double quotes


t = 'Python' # string with single quotes

4. Mapping Type

 dict (Dictionary): An unordered collection of key-value pairs. Keys must be


unique and immutable, while values can be of any type. A dictionary is
mutable, meaning its content can be changed.

d = {'name': 'John', 'age': 30, 'city': 'New York'}

5. Set Types

These represent collections of unique values.

 set: Unordered collection of unique items. It doesn't allow duplicate values.


Sets are mutable.

s = {1, 2, 3, 4}

 frozenset: Similar to a set, but it is immutable (cannot be modified after


creation).

fs = frozenset([1, 2, 3, 4])

6. Boolean Type

 bool: Represents either True or False. It is used to store Boolean values and
is commonly used in conditional statements.

a = True
b = False

7. Binary Types

These types deal with binary data, such as streams of bytes.

 bytes: Immutable sequence of bytes. Often used to represent data in


memory or on disk.

b = b'Hello'
 bytearray: Mutable sequence of bytes, which is like a list of bytes.

ba = bytearray([65, 66, 67]) # bytearray representing 'ABC'

 memoryview: A memory view object allows access to the internal data of an


object without copying it. This is typically used when working with large data
structures to avoid the overhead of copying.

mv = memoryview(b'Hello')

8. None Type

 None: This represents the absence of a value or a null value. It is often used
to represent uninitialized variables or as a placeholder.

a = None # No value assigned

Type Conversion (Typecasting)

Python provides several functions to convert one data type into another. Here are
some common type conversion functions:

 int(): Converts to an integer.

a = int("10") # Converts the string "10" to an integer

 float(): Converts to a float.

b = float("10.5") # Converts the string "10.5" to a float

 str(): Converts to a string.

c = str(123) # Converts the integer 123 to a string

 list(): Converts to a list.

d = list((1, 2, 3)) # Converts a tuple (1, 2, 3) to a list

 tuple(): Converts to a tuple.

e = tuple([1, 2, 3]) # Converts a list [1, 2, 3] to a tuple

In Python, a variable is essentially a name that refers to a value or an object. When


you create a variable, you are essentially creating a container that holds data, and
that container can hold different types of data (like numbers, strings, lists, etc.).
Variables are fundamental to writing programs as they allow you to store,
manipulate, and retrieve data throughout your code.

Key Concepts about Variables in Python:

1. Assignment: In Python, you create a variable by assigning a value to a


name using the = operator. The value can be of any data type, such as an
integer, string, list, etc.

Example:

x = 10 # Assigns the value 10 to variable x


name = "John" # Assigns the string "John" to variable name

2. Dynamic Typing: Python is dynamically typed, which means that you don't
need to declare the type of a variable when you create it. The type is
determined automatically based on the value assigned to the variable.

Example:

x=5 # x is an integer
x = "Hello" # Now x is a string

3. Variable Naming Rules: When naming variables in Python, you must follow
a few rules:
o A variable name can only contain letters (a-z, A-Z), digits (0-9), and
underscores (_).
o A variable name cannot start with a digit.
o Python is case-sensitive, so myVar and myvar are two different
variables.
o Reserved words (keywords like if, for, while, etc.) cannot be used as
variable names.

Valid variable names:

my_var = 10
myVar = 20
_myVar = 30
var_2 = 40

Invalid variable names:

2myVar = 100 # Cannot start with a digit


my-var = 200 # Hyphen is not allowed
class = 300 # "class" is a reserved keyword

4. Assigning Multiple Values: You can assign values to multiple variables in a


single line using a comma , to separate the variable names, and then a
corresponding set of values to assign.
Example:

x, y, z = 5, 10, 15 # Assigns 5 to x, 10 to y, and 15 to z

Similarly, you can assign the same value to multiple variables at once:

python
Copy
a = b = c = 100 # All three variables will have the value 100

5. Global vs. Local Variables:


o Global variables are defined outside of any function and are
accessible anywhere in the code.
o Local variables are defined inside a function and can only be
accessed within that function.

Example:

global_var = 50 # Global variable

def example_function():
local_var = 10 # Local variable
print(local_var) # Prints the local variable

example_function() # This works fine


print(global_var) # This works fine as global variable is accessible outside
function
# print(local_var) # Error: local_var is not accessible outside the function

6. Mutable vs Immutable Variables:


o Immutable types are those whose values cannot be changed once
they are created. Examples of immutable types are integers, floats,
strings, and tuples.
o Mutable types are those whose values can be changed after they are
created. Examples include lists, dictionaries, and sets.

Example:

# Immutable
x = 10
x = x + 5 # This creates a new integer, rather than modifying the existing
one

# Mutable
lst = [1, 2, 3]
lst.append(4) # The list is modified in place

7. Constants: In Python, you can create a constant by using uppercase letters


for the variable name to indicate that the value should not change. However,
Python does not have a built-in mechanism to enforce constant values (i.e.,
variables are still technically mutable).

Conventionally, you use all caps for constants:

PI = 3.14159
MAX_USERS = 100

Even though these are considered "constants," the values could still
technically be changed in the code.

8. Variable Scope: The scope of a variable determines where in the code the
variable can be accessed. There are two main types of scope:
o Local Scope: A variable that is defined inside a function can only be
accessed inside that function.
o Global Scope: A variable that is defined outside of any function can
be accessed from anywhere in the code.

Example:

global_variable = 100 # Global variable

def my_function():
local_variable = 10 # Local variable
print(local_variable) # Accessing local variable inside function

my_function()
print(global_variable) # Accessing global variable outside function
# print(local_variable) # Error: local_variable is not accessible here

9. The del Keyword: The del keyword is used to delete a variable, meaning it
removes the variable from the memory.

Example:

x=5
del x # Deletes the variable x
# print(x) # Error: x is no longer defined

10.Rebinding Variables: Python allows you to reassign a variable to another


value, essentially rebinding the variable to a new object.

a = 10 # a is bound to the integer 10


a = "hello" # a is now bound to the string "hello"
a = [1, 2, 3] # a is now bound to a list

11.Type Checking: You can check the type of a variable using the type()
function to understand the type of value it holds.
a = 10
print(type(a)) # <class 'int'>

b = "hello"
print(type(b)) # <class 'str'>

Summary:

 Variables are names that point to values (objects).


 Python uses dynamic typing, so you don't have to specify the type when
defining a variable.
 A variable can hold different types of data throughout the code (such as
integers, strings, lists, etc.).
 Python variables have local and global scopes, and their types can be
mutable or immutable.
 You can rebind variables, delete them with del, and check their type with
type().

You might also like