Introduction to Python-day 3 (1)
Introduction to Python-day 3 (1)
Python supports various data types, these data types defines the operations
possible on the variables and the storage method.
▪ Variables can hold values of different data types.
Python is a dynamically typed language hence
we need not define the type of the variable while
declaring it.
▪ The interpreter implicitly binds the value with its
type.
▪ Python enables us to check the type of the variable
used in the program.
▪ Python provides us the type() function which
returns the type of the variable passed.
▪ A=10
▪ b="Hi Python"
▪ c = 10.5
▪ print(type(a));
▪ print(type(b));
▪ print(type(c));
Python Numbers
There are three numeric types in Python:
▪ int
▪ float
▪ complex
Eg:
x = 1 # int
y = 2.8 # float
z = 1j # complex
Type Conversion
• In Explicit Type Conversion, users convert the data type of an object to required
data type. We use the predefined functions like int(), float(), str(), etc to perform
explicit type conversion.
• This type of conversion is also called typecasting because the user casts (changes)
the data type of the objects.
• Syntax :
• <required_datatype>(expression)
Type Conversion
x = 1 # int
y = 2.8 # float
z = 1j # complex
print('G' in x) # True
print('good' not in x) #True
print('Good' not in x) #False
print(3 in y) #True
Identity Operators
▪ is and is not are the identity operators in
Python. They are used to check if two
values (or variables) are located on the
same part of the memory. Two variables
that are equal does not imply that they are
identical.
Identity Operators
String
▪ Creating a String
print(a)
Strings are Arrays
Strings in Python are arrays of bytes representing unicode
characters. However,
Python does not have a character data type, a single character is
simply a string with a length of 1.
Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])
Slicing
▪ You can return a range of characters by using the slice syntax.
▪ Specify the start index and the end index, separated by a colon, to return a
part of the string.
▪ start_pos default value is 0, the end_pos default value is the length of string
and step default value is 1.
b = "Hello, World!"
print(b[2:5])
# output:llo
Get the characters from position 2 to position 5 (not included)
slice() Parameters
▪ slice() mainly takes three parameters which have the same
meaning in both constructs:
▪ start - starting integer where the slicing of the object starts
▪ stop - integer until which the slicing takes place. The slicing stops
at index stop - 1.
▪ step - integer value which determines the increment between
each index for slicing
a = [1, 2, 3, 4, 5, 6, 7, 8]
print(a[:5]) # prints [1, 2, 3, 4, 5]
print(a[2:]) # prints [3, 4, 5, 6, 7, 8]
print(a[2:5]) # prints [3, 4, 5]
print(a[2:7:2]) # prints [3, 5, 7]