Data Types in Python
- In programming languages, data types are important subjects.
- Variables can store data of different data types.
- In Python, the moment you assign a value to a variable, that’s when the data type is set for the variable.
Data types define the type of data a variable can hold and the operations that can be performed on that data. Here are some of the common data types in Python:
- Integers: Integers represent whole numbers, positive, negative, or zero. They are typically stored using 4 or 8 bytes of memory.
- Floating-point numbers: Floating-point numbers represent real numbers, which include numbers with decimal points. They are stored using 4 or 8 bytes of memory and provide a wider range of values than integers, but come with a loss of precision.
- Strings: Strings are sequences of characters, used to represent text data. In Python, strings are enclosed in single quotes (‘), double quotes (“), or triple quotes (“”” or ”’). Triple-quoted strings can span multiple lines.
- Booleans: Booleans represent logical values: True or False. They are used in conditional statements to control the flow of your program.
- Lists: Lists are used to store collections of items ordered by index. Items in a list can be of different data types, and lists are mutable, meaning you can change the content of the list after it is created. Lists are enclosed in square brackets
[]
. - Tuples: Tuples are similar to lists, but they are immutable, meaning their contents cannot be changed after they are created. Tuples are enclosed in parentheses
()
. - Dictionaries: Dictionaries are used to store collections of key-value pairs. They are unordered, meaning the order in which you add items to a dictionary does not necessarily reflect the order in which they are retrieved. Dictionaries are enclosed in curly braces
{}
.
Numeric Types:
- int: Integers represent whole numbers, positive, negative, or zero. They are typically stored using 4 or 8 bytes of memory.
- float: Floating-point numbers represent real numbers, which include numbers with decimal points. They are stored using 4 or 8 bytes of memory and provide a wider range of values than integers, but come with a loss of precision.
Text Type:
- str: Strings are sequences of characters, used to represent text data. In Python, strings are enclosed in single quotes (‘), double quotes (“), or triple quotes (“”” or ”’). Triple-quoted strings can span multiple lines.
Logical Type:
- bool: Booleans represent logical values: True or False. They are used in conditional statements to control the flow of your program.
Sequence Types:
- list: Lists are used to store collections of items ordered by index. Items in a list can be of different data types, and lists are mutable, meaning you can change the content of the list after it is created. Lists are enclosed in square brackets
[]
. - tuple: Tuples are similar to lists, but they are immutable, meaning their contents cannot be changed after they are created. Tuples are enclosed in parentheses
()
.
Mapping Type:
- dict: Dictionaries are used to store collections of key-value pairs. They are unordered, meaning the order in which you add items to a dictionary does not necessarily reflect the order in which they are retrieved. Dictionaries are enclosed in curly braces
{}
.
Binary Types:
- bytes: Used to represent binary data, such as image files or compressed data.
- bytearray: A mutable version of bytes. You can change the elements of a bytearray after it is created.
- memoryview: Provides a way to access the memory of a Python object without copying it.
To know dataype please run below command
x=1
print(type(x))
# String
x = "Hello World" # str
# Integer
x = 20 # int
# Floating point
x = 20.5 # float
# Complex number
x = 1j # complex
# List
x = ["apple", "banana", "cherry"] # list
# Tuple
x = ("apple", "banana", "cherry") # tuple
# Range
x = range(6) # range
# Dictionary
x = {"name" : "John", "age" : 36} # dict
# Set
x = {"apple", "banana", "cherry"} # set
# Frozen Set
x = frozenset(("apple", "banana", "cherry")) # frozenset
# Boolean
x = True # bool
# Bytes
x = b"Hello" # bytes
# Byte array
x = bytearray(5) # bytearray
# Memory view
x = memoryview(bytes(5)) # memoryview
# Demonstrates reassignment of different data types to 'x'
x = str("Hello World") # str
x = int(20) # int
x = float(20.5) # float
x = complex(1j) # complex
x = list(("apple", "banana", "cherry")) # list
x = tuple(("apple", "banana", "cherry")) # tuple
x = range(6) # range
x = dict(name="John", age=36) # dict
x = set(("apple", "banana", "cherry")) # set
x = frozenset(("apple", "banana", "cherry")) # frozenset
Numbers in Python
- There are 3 number types available in Python:
- int
- float
- Complex
- int: It’s a whole number (positive or negative) without decimals, unlimited length.
- float: It’s a decimal number (positive or negative) containing one or more decimals.
- complex: Complex numbers are written with “j” as the imaginary part.
Data Type Conversion & Type Casting in Python
Strings in Python
Strings
- Strings in Python are surrounded by single quote or double quote.
- To get multiline strings, we should use three quotes.
- Strings in Python are like an array of characters. Hence, we can access characters in strings using indexes. Note, Python doesn’t have a character data type.
- Since strings are like an array of characters, we can loop through them.
- The
in
keyword can be used to check for a certain phrase or character in a string. - To concatenate, use the
+
symbol.
Slicing Strings
- We can return a range of characters by using slice syntax:
= "Hello" print(a[2:4]) # Outputs 'll'
- Use Negative Index to start slice from the end of the string:
= "Hello" print(a[-5:-2]) # Outputs 'Hel'
Format Strings in Python
Format Strings
- We cannot combine strings and numbers directly using + symbol.
- But we can combine strings and numbers using
format()
method. format()
method takes the passed arguments, formats them, and places them in string where placeholders{}
are there.
name = "Alice"
age = 30
message = "My name is {} and I am {} years old."
print(message.format(name, age))
output:
My name is Alice and I am 30 years old.
#if both are string
x= "my age is"
y="29"
print(x + y)
#if one is string and other integer
x= "my age is"
y=29
print(x + y)
#solution to print either datatype using format
x= "my age is "
y=29
print("my age is {}".format(y))
Escape Characters in Python
Escape Characters
- We will use escape characters to insert characters that are invalid in a string.
- Escape character is a backslash
\
followed by the character we want to insert.
Here are some common uses of escape characters:
\n
: Inserts a newline in the text at that point.\t
: Inserts a tab in the text at that point.\\
: Inserts a backslash character in the string.\'
: Allows for a single quote character to be included in a single-quoted string.\"
: Allows for a double quote character to be included in a double-quoted string.
print("He said, \"Hello, how are you?\"")
output
He said, "Hello, how are you?"
String Methods in Python
Strings have a set of built-in methods/functions in Python. We will be exploring a few important built-in methods of strings:
- upper(): Converts a string into upper case.
- lower(): Converts a string into lower case.
- index(): Searches the string for a specified value and returns the position of where it was found.
- replace(): Returns a string where a specified value is replaced with a specified value.
- split(): Splits the string at the specified separator and returns a list.
- strip(): Returns a trimmed version of the string.
text = "hello world"
print(text.upper()) # Output: "HELLO WORLD"
text = "HELLO WORLD"
print(text.lower()) # Output: "hello world"
text = "hello world"
print(text.index("world")) # Output: 6
text = "hello world"
print(text.replace("world", "Python")) # Output: "hello Python"
text = "hello world"
print(text.replace("world", "Python")) # Output: "hello Python"
text = "hello world"
print(text.split(" ")) # Output: ['hello', 'world']
text = "hello"
print(text.isalpha()) # Output: True
text = "hello123"
print(text.isalpha()) # Output: False
number = "12345"
print(number.isdigit()) # Output: True
number = "12345abc"
print(number.isdigit()) # Output: False
text = "hello123"
print(text.isalnum()) # Output: True
text = "hello 123"
print(text.isalnum()) # Output: False
space = " "
print(space.isspace()) # Output: True
space = " a "
print(space.isspace()) # Output: False
title = "Hello World"
print(title.istitle()) # Output: True
title = "Hello world"
print(title.istitle()) # Output: False
text = "hello world"
print(text.islower()) # Output: True
text = "HELLO WORLD"
print(text.isupper()) # Output: True
Booleans in Python
bool()
bool()
function allows you to evaluate a value and returnTrue
orFalse
.- Any string will return
True
, except an empty string (""
). - Any number will return
True
, except0
. - Any list, tuple, set will return
True
, except empty ones[], (), {}
.
Examples for Strings:
print(bool("Hello World")) # Output: True
print(bool("")) # Output: False
Examples for Numbers:
print(bool(1)) # Output: True
print(bool(0)) # Output: False
print(bool(-10)) # Output: True
Examples for Collections:
print(bool([1, 2, 3])) # Output: True
print(bool([])) # Output: False
print(bool((1, 2))) # Output: True
print(bool(())) # Output: False
print(bool({1, 2})) # Output: True
print(bool(set())) # Output: False
Using bool()
with None
:
print(bool(None)) # Output: False
Logical Context:
a = []
if a:
print("The list is not empty.")
else:
print("The list is empty.")
# Output:
Operators in Python
Operators in Python
Operators are used to perform operations on values and variables.
Python supports a variety of operators, including:
- Arithmetic operators (+, -, *, /, %, //, **)
- Comparison operators (==, !=, <, >, <=, >=)
- Assignment operators (=, +=, -=, *=, /=, %=)
- Logical operators (and, or, not)
- Bitwise operators (&, |, ^, <<, >>)
- Identity operators (is, is not)
- Membership operators (in, not in)
Arithmetic Operators in Python
Operator | Description | Example | Output |
---|---|---|---|
+ | Addition | x = 5 + 3 | 8 |
– | Subtraction | x = 10 – 2 | 8 |
* | Multiplication | x = 4 * 5 | 20 |
/ | Division (results in a float) | x = 10 / 3 | 3.3333 |
// | Floor division (rounds down to nearest whole number) | x = 10 // 3 | 3 |
% | Modulus (remainder after division) | x = 10 % 3 | 1 |
** | Exponentiation (x to the power of y) | x = 2 ** 3 | 8 |
Python
# Addition
x = 5 + 3
print(x) # Output: 8
# Subtraction
y = 10 - 2
print(y) # Output: 8
# Multiplication
z = 4 * 5
print(z) # Output: 20
# Division (results in a float)
a = 10 / 3
print(a) # Output: 3.3333
# Floor division (rounds down to nearest whole number)
b = 10 // 3
print(b) # Output: 3
# Modulus (remainder after division)
c = 10 % 3
print(c) # Output: 1
# Exponentiation (x to the power of y)
d = 2 ** 3
print(d) # Output: 8
Comparison Operators in Python
x = 5
y = 7
# Equal to (==)
print(f"{x} == {y}: {x == y}") # False
# Not equal to (!=)
print(f"{x} != {y}: {x != y}") # True
# Greater than (>)
print(f"{x} > {y}: {x > y}") # False
# Less than (<)
print(f"{x} < {y}: {x < y}") # True
# Greater than or equal to (>=)
print(f"{x} >= {y}: {x >= y}") # False
# Less than or equal to (<=)
print(f"{x} <= {y}: {x <= y}") # True
# This code checks if a number is greater than 10 and less than 20
number = 15
if number > 10 and number < 20:
print("The number is between 10 and 20")
else:
print("The number is not between 10 and 20")
# This code checks if a username is "admin" or "user"
username = "user"
if username == "admin" or username == "user":
print("Valid username")
else:
print("Invalid username")
# This code checks if a file does not exist
file_name = "data.txt"
if not os.path.exists(file_name):
print("The file does not exist")
else:
print("The file exists")
x = 5
# AND (and)
print(f"{x} > 0 and {x} < 10: {x > 0 and x < 10}") # True
# OR (or)
print(f"{x} > 0 or {x} > 10: {x > 0 or x > 10}") # True
# NOT (not)
print(f"not({x} > 0 and {x} < 10): {not(x > 0 and x < 10)}") # False
# This code checks if a number is greater than 10 and less than 20
number = 15
if number > 10 and number < 20:
print("The number is between 10 and 20")
else:
print("The number is not between 10 and 20")
# This code checks if a username is "admin" or "user"
username = "user"
if username == "admin" or username == "user":
print("Valid username")
else:
print("Invalid username")
# This code checks if a file does not exist (using the `os` module)
import os
file_name = "data.txt"
if not os.path.exists(file_name):
print("The file does not exist")
else:
print("The file exists")
Identity Operators in Python
Identity operators in programming, specifically focusing on their usage in Python:
- is: Returns
True
if both variables point to the same object in memory. - is not: Returns
True
if both variables do not point to the same object in memory.
To know memory address location for values use id()
x = 10
print(id(x))
for eg x =y only if both memory address is same
# Define two lists with the same content
list1 = [1, 2, 3]
list2 = [1, 2, 3]
# Check if list1 and list2 refer to the same object
print(list1 is list2) # Output will be False, as they are two different objects
# Check if list1 and list2 do not refer to the same object
print(list1 is not list2) # Output will be True
# Define another list referencing list1
list3 = list1
# Check if list1 and list3 refer to the same object
print(list1 is list3) # Output will be True, as they reference the same object
# Check if list1 and list3 do not refer to the same object
print(list1 is not list3) # Output will be False
In this example:
is
operator checks if two variables refer to the same object in memory.is not
operator checks if two variables do not refer to the same object in memory.
Remember, is
and is not
compare object identity, while ==
compares object equality (i.e., whether the objects referred to have the same content).
Membership Operators in Python
These operators are used to check if a specified value is present in an object like strings, lists, tuples, or dictionaries. The operators discussed are:
in
: Returns True if a sequence with the specified value is present in the object.not in
: Returns True if a sequence with the specified value is not present in the object.
Example 1: Using in
with a List
# Define a list of fruits
fruits = ['apple', 'banana', 'cherry']
# Check if 'banana' is in the list
print('banana' in fruits) # Output: True
# Check if 'orange' is in the list
print('orange' in fruits) # Output: False
Example 2: Using not in
with a String
# Define a string
sentence = "Hello, world!"
# Check if 'Hello' is not in the string
print('Goodbye' not in sentence) # Output: True
# Check if 'world' is not in the string
print('world' not in sentence) # Output: False
Example 3: Using in
with a Dictionary
# Define a dictionary
person = {"name": "John", "age": 30}
# Check if a key 'name' exists in the dictionary
print('name' in person) # Output: True
# Check if a key 'address' exists in the dictionary
print('address' in person) # Output: False
Example 4: Using in
to Check Values in a Dictionary
# Using 'in' to check for values (need to specify looking in values)
print(30 in person.values()) # Output: True
print('John' in person.values()) # Output: True
Bitwise Operators AND(&), OR(|), XOR(^) ,NOT(~), Left Shift, Right Shift in Pythonin Python
an overview of bitwise operators, which are used for manipulating data at the bit level in programming. Here’s a brief explanation of each operator listed:
- AND (
&
): This operator compares each bit of its first operand to the corresponding bit of its second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, it’s set to 0. - OR (
|
): This operator compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, it’s set to 0. - XOR (
^
): This operator is used to compare two bits, being true if the bits in the operands are different (i.e., one is 1, the other is 0), and false if they are the same. - NOT (
~
): This is a unary operator that inverts the bits of its operand (i.e., changes 0 to 1 and 1 to 0). - Zero fill left shift (
<<
): This operator shifts the bits of its first operand to the left by the number of positions specified by the second operand. New bits on the right are filled with zeros. - Signed right shift (
>>
): This operator shifts the bits of its first operand to the right by the number of positions specified by the second operand. If the value is a signed number, the leftmost bits are filled with the sign bit (the highest-order bit of the original number) to preserve the sign of the number.
AND Operator (&
)
a = 12 # in binary: 1100
b = 10 # in binary: 1010
result = a & b # in binary: 1000, which is 8 in decimal
print("AND Result:", result)
OR Operator (|
)
a = 12 # in binary: 1100
b = 10 # in binary: 1010
result = a | b # in binary: 1110, which is 14 in decimal
print("OR Result:", result)
XOR Operator (^
)
a = 12 # in binary: 1100
b = 10 # in binary: 1010
result = a ^ b # in binary: 0110, which is 6 in decimal
print("XOR Result:", result)
NOT Operator (~
)
a = 12 # in binary: 1100
result = ~a # in binary: ...11110011 (this is a 32-bit representation)
print("NOT Result:", result)
Zero Fill Left Shift Operator (<<
)
a = 12 # in binary: 1100
shifted = a << 2 # in binary: 110000, which is 48 in decimal
print("Left Shift Result:", shifted)
Signed Right Shift Operator (>>
)
a = 12 # in binary: 1100
shifted = a >> 2 # in binary: 11, which is 3 in decimal
print("Right Shift Result:", shifted)