Datatypes in Python
Datatypes in Python
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
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.).
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.
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")
• 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:
Correct:
for i in range(3):
print(i) # Indented with 4 spaces
for i in range(3):
print(i) # This line uses 4 spaces
print(i) # This line uses a tab, leading to an error
Indentation is used with control structures such as if, for, while, and functions.
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.
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.
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:
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}")