0% found this document useful (0 votes)
10 views13 pages

Datatypes in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views13 pages

Datatypes in Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

Python has several built-in data types that are used to store different kinds of

data. Here’s an overview of the most common ones:


1. Numeric Types:
• int: Integer numbers (e.g., 5, -10)
• float: Floating-point numbers (e.g., 5.7, -2.3)
• complex: Complex numbers (e.g., 1+2j, 3-5j)
x=5 # int
y = 3.14 # float
z = 2 + 3j # complex
2. Sequence Types:
• str: Strings, used for text (e.g., 'Hello', "Python")
• list: Ordered, mutable collections of items (e.g., [1, 2, 3], ['apple',
'banana'])
• tuple: Ordered, immutable collections of items (e.g., (1, 2, 3), ('apple',
'banana'))
s = "Hello" # str
my_list = [1, 2, 3, 4] # list
my_tuple = (1, 2, 3, 4) # tuple
3. Mapping Type:
• dict: Key-value pairs, also called dictionaries (e.g., {'name': 'John', 'age':
25})
person = {"name": "Alice", "age": 30}
4. Set Types:
• set: Unordered collections of unique items (e.g., {1, 2, 3}, {'apple',
'banana'})
• frozenset: Immutable version of a set
my_set = {1, 2, 3, 4} # set
frozen = frozenset([1, 2, 3, 4]) # frozenset

5. Boolean Type:
• bool: Represents True or False
is_true = True
is_false = False
6. Binary Types:
• bytes: Immutable sequences of bytes (e.g., b'hello')
• bytearray: Mutable sequences of bytes (e.g., bytearray(b'hello'))
• memoryview: Provides memory access to byte data
byte_data = b"Hello" # bytes
mutable_bytes = bytearray(5) # bytearray
view = memoryview(byte_data) # memoryview
7. None Type:
• None: Represents the absence of a value or a null value
x = None
8. Range Type:
• range: Represents a sequence of numbers
numbers = range(1, 10)
Each data type in Python has its own specific methods and operations
associated with it. You can check the type of any object using the type()
function:
print(type(x)) # Outputs the type of x
TYPE CONVERSION
Type conversion (or type casting) in Python allows you to convert a value of
one data type to another. Python supports two types of type conversion:
1. Implicit Type Conversion:
Python automatically converts one data type to another without explicit
instruction. This usually happens in expressions where mixed types are
used.
# Implicit conversion from int to float
Num1 = 5
Num2 = 3.5

result = Num1 + Num2 # int is implicitly converted to float


print(result) # Output: 8.5
print(type(result)) # Output: <class 'float'>
2. Explicit Type Conversion:
Also known as type casting, this is when you manually convert a data type into
another. Python provides several built-in functions for this.
Common Explicit Type Conversion Functions:
• int(): Converts to an integer
• float(): Converts to a floating-point number
• str(): Converts to a string
• list(): Converts to a list
• tuple(): Converts to a tuple
• set(): Converts to a set
• dict(): Converts to a dictionary (only valid for iterable objects like lists of
tuples)
• bool(): Converts to a boolean (True or False)
Examples of Explicit Conversion:
1. Converting to Integer (int()):
x = "10"
y = 3.7
z = int(x) # String to integer
w = int(y) # Float to integer (truncated)
print(z) # Output: 10
print(w) # Output: 3

2. Converting to Float (float()):


x = "10.5"
y=2
z = float(x) # String to float
w = float(y) # Integer to float
print(z) # Output: 10.5
print(w) # Output: 2.0

3. Converting to String (str()):


x = 100
y = 3.14
z = str(x) # Integer to string
w = str(y) # Float to string
print(z) # Output: '100'
print(w) # Output: '3.14'

4. Converting to List (list()):


x = "Hello"
y = (1, 2, 3)
z = list(x) # String to list of characters
w = list(y) # Tuple to list
print(z) # Output: ['H', 'e', 'l', 'l', 'o']
print(w) # Output: [1, 2, 3]

5. Converting to Tuple (tuple()):


x = [1, 2, 3]
z = tuple(x) # List to tuple
print(z) # Output: (1, 2, 3)

6. Converting to Set (set()):


x = [1, 2, 2, 3, 3, 4]
z = set(x) # List to set (duplicates removed)
print(z) # Output: {1, 2, 3, 4}

7. Converting to Dictionary (dict()):


x = [("name", "Alice"), ("age", 25)]
z = dict(x) # List of tuples to dictionary
print(z) # Output: {'name': 'Alice', 'age': 25}

8. Converting to Boolean (bool()):


x=0
y = ""
z = bool(x) # 0 converts to False
w = bool(y) # Empty string converts to False
print(z) # Output: False
print(w) # Output: False

Notes:
• When converting between incompatible types (like converting a string that
contains non-numeric characters to an integer), Python will raise a
ValueError.
• Implicit conversion usually occurs in cases where no information is lost,
whereas explicit conversion is necessary when you're converting between
types that don't naturally fit together.
Indentation in Python
In Python, indentation is used to define the structure and hierarchy of code blocks. Unlike
many other programming languages that use braces ({})to indicate blocks of code, Python
uses indentation to delineate which lines of code are part of a specific block (such as within
functions, loops, conditionals, etc.).

Key Points about Indentation in Python:

1. Mandatory Indentation:

In Python, indentation is required. If you fail to properly indent your code, Python will raise
an IndentationError. It is not merely for readability but is part of the syntax.

Example:

if True:
print("This line is indented and part of the if block")
print("This line is outside the if block")

In this example, the first print() is indented, meaning it belongs to the if block, while the
second print() is not indented and runs regardless of the if condition.

2. Defining Code Blocks:

Blocks of code in Python are defined by their indentation level. Any code that is indented
after a control structure (such as if, for, while, def, etc.) is considered part of that block.

Example:

def my_function():
print("This is part of the function block")
if True:
print("This is inside the if block within the function")

print("This is outside the function block")

• The print("This is part of the function block") line is part of my_function() because it is
indented.
• The nested print("This is inside the if block within the function") is indented even further and
belongs to the if block inside the function.

3. Consistent Indentation:

• You must maintain consistent indentation throughout your code. Python


recommends using 4 spaces for each level of indentation.
• Mixing spaces and tabs for indentation will result in a TabError.

Correct:
for i in range(3):
print(i) # Indented with 4 spaces

Incorrect (Mixing Tabs and Spaces):

for i in range(3):
print(i) # This line uses 4 spaces
print(i) # This line uses a tab, leading to an error

This will result in the following error:

TabError: inconsistent use of tabs and spaces in indentation

4. Indentation in Control Structures:

Indentation is used with control structures such as if, for, while, and functions.

Example with if block:

age = 20
if age >= 18:
print("You are an adult")
else:
print("You are a minor")

In this case, both the if and else branches have their own indented code blocks.

Example with a loop:

for i in range(3):
print(i) # This is indented, part of the loop
print("Loop finished") # This is outside the loop, no indentation

5. Nested Indentation:

Python allows nested blocks, and each new level of nesting requires additional indentation.

Example of Nested Code Blocks:

for i in range(3):
if i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")

Here, the if and else statements are indented under the for loop, and the print() statements are
further indented under the if and else.

6. Indentation Errors:

If indentation is not done correctly, Python will raise an IndentationError. This could happen
due to inconsistent use of tabs and spaces or incorrect indentation levels.
Example of Incorrect Indentation:

if True:
print("This will raise an IndentationError") # No indentation
IndentationError: expected an indented block

Summary:

• Python uses indentation to define blocks of code.


• 4 spaces per indentation level is the standard (as per PEP 8).
• Indentation is required for control structures (if, for, while, def, class, etc.).
• Incorrect or inconsistent indentation leads to IndentationError or TabError.

Ensuring proper and consistent indentation is essential for writing error-free and readable
Python code.

Python Syntax
Python is designed to be simple and readable, which is reflected in its syntax.
1. Case Sensitivity
• Python is case-sensitive, meaning variable and Variable are treated as
different identifiers.
myVariable = 5
MyVariable = 10
print(myVariable) # Outputs: 5
print(MyVariable) # Outputs: 10
2. Statements and Line Breaks
• Each line in Python generally corresponds to a statement. Multiple
statements can be written on a single line by separating them with a
semicolon ;.
x=5
y = 10
print(x); print(y) # Both prints can be on the same line, separated by a
semicolon
• To break a long statement into multiple lines, use the backslash \.
total = 100 + 200 + \
300 + 400
• Parentheses (), brackets [], or curly braces {} can also automatically
continue statements across multiple lines.
total = (100 + 200 +
300 + 400)
3. Indentation
• Python uses indentation (spaces or tabs) to define blocks of code. Each
block (such as in loops, functions, or conditionals) must be consistently
indented, usually with 4 spaces.
if True:
print("This is indented and part of the if block")
print("This is outside the block")
Incorrect indentation will raise an IndentationError.
4. Comments
• Single-line comments are written using the hash (#) symbol.
• Multi-line comments are typically written using triple quotes ''' or """.
# This is a single-line comment

"""
This is a multi-line comment
spread across multiple lines.
"""
5. Variables and Assignment
• Variables in Python are created when you assign a value to them. No
need to declare the type explicitly.
• Python uses the = sign for assignment.
x = 5 # Integer
name = "Alice" # String
price = 19.99 # Float
• Variable names must start with a letter or an underscore, followed by
letters, numbers, or underscores.

6. Data Types
• Common Python data types include:
o int (integer): x = 10
o float (floating point): x = 10.5
o str (string): x = "Hello"
o bool (boolean): x = True
o list: x = [1, 2, 3]
o tuple: x = (1, 2, 3)
o dict: x = {"name": "Alice", "age": 25}
o set: x = {1, 2, 3}
7. Input/Output
• The print() function is used for output, and input() is used to get input
from the user.
name = input("Enter your name: ")
print("Hello, " + name)
8. Conditional Statements
• if, elif, and else are used for conditional branching.
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
9. Loops
• Python supports two main types of loops: for and while.
For Loop:
for i in range(5):
print(i) # Prints numbers from 0 to 4
While Loop:
count = 0
while count < 5:
print(count)
count += 1
10. Functions
• Functions in Python are defined using the def keyword, followed by the
function name and parentheses ().
def greet(name):
print(f"Hello, {name}")

greet("Alice") # Outputs: Hello, Alice


11. Exceptions
• Python uses try, except, else, and finally for exception handling.
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
else:
print("No errors occurred")
finally:
print("This block is always executed")
12. Modules and Imports
• Python code can be organized into modules and packages. You can
import them using the import keyword.
import math
print(math.sqrt(16)) # Outputs: 4.0
• You can import specific functions or variables:
from math import sqrt
print(sqrt(16)) # Outputs: 4.0
Summary :
• Case-sensitive.
• Use indentation (usually 4 spaces) to define code blocks.
• Variables are dynamically typed (no explicit type declaration needed).
• Comments are made using # or triple quotes for multi-line comments.
• Use print() for output and input() for user input.
• Conditional statements use if, elif, else.
• Loops: for, while.
• Functions are defined using def.
• Handle errors with try, except.
• Modules and libraries can be imported with import.

You might also like