Day 2: Data types and strings in Python
Data Types:
Data types are an essential concept in programming. They represent the different types of data that a program needs to manipulate and process.
Python, like many programming languages, supports several built-in data types. Here are some of the common data types in Python:
Data Types in Python
Python supports a variety of data types:
Numeric types:
int
,float
,complex
Sequence types:
list
,tuple
,range
Mapping type:
dict
Set type:
set
,frozenset
Boolean type:
bool
Binary types:
bytes
,bytearray
,memoryview
None type:
NoneType
Python data types determine how data is stored and operated upon.
Numeric Types
int
: Stores integers.
a = 10
type(a)
# <class 'int'>
float
: Stores floating point numbers.
b = 10.5
type(b)
# <class 'float'>
complex
: Stores complex numbers with real and imaginary parts.
c = 1 + 2j
type(c)
# <class 'complex'>
Sequence Types
list
: Stores ordered collections of items.
fruits = ["Apple", "Banana", "Cherry"]
type(fruits)
# <class 'list'>
tuple
: Stores immutable ordered collections.
coordinates = (3, 5)
type(coordinates)
# <class 'tuple'>
range
: Generates a sequence of numbers.
Mapping Type
dict
: Stores data as key-value pairs.
capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome'}
type(capital_city)
# <class 'dict'>
Other Types
set
: Stores unordered collections of unique items.bool
: StoresTrue
orFalse
values.str
: Stores string values.NoneType
: Represents the absence of a value.
Data types allow Python to:
Allocate memory efficiently
Perform type checking
Specify function parameters Hope this helps! Let me know if you have any other questions.
String Data Type in Python
In Python, a string is a sequence of characters. Strings are defined either using single quotes ('...') or double quotes ("...") with the difference being that double quotes allow interpolation of variables using the $ sign.
string1 = 'Hello' string2 = "Hello"
Strings are immutable, which means you cannot change an individual character in a string, you have to create a new string.
Some key facts about strings in Python:
Strings can be concatenated using the + operator or the format() method
Strings can be sliced using [] to get substrings
Length of a string can be found using the len() function
Strings can be checked for substrings using the in and not in operators
Strings have many useful methods like upper(), lower(), split(), replace(), etc.
For example:
string = "Hello World!"
# Concatenate
string2 = string + " Welcome!"
# Slice
string3 = string[2:5]
# Length
length = len(string)
# Check
if "Hello" in string:
print("Yes")
# Upper case
string_upper = string.upper()
# Replace
string_new = string.replace("World", "Universe")
In the web search result, we also saw:
Strings can be assigned to variables
Multiline strings can be defined using triple quotes
Strings can be indexed and sliced like arrays
Hope this helps! Let me know if you have any other questions.