Python Datatypes

    Python Datatypes

      Python is a popular programming language that is widely used for web development, scientific computing, data analysis, artificial intelligence, and more.

            In this blog post, we will provide an overview of the most commonly used datatypes in Python.

Datatypes in python:

  
      There are mainly four types of basic primitive Datatypes,
available in python

       Numeric: Int, Float and Complex

       Sequence:  String, List and Tuple

       Sets

       Dictionary


Integer datatypes:

        Integer datatypes are represent whole integer values and representing using "int()" class,
 we can store positive and negative values. 
        
           ---> Directly assigning an integer value to a variable or using a "int()" class
            
                                   example:               x = 1
         y = 3565622255488771
 z = -3255522

   print(type(x))
   print(type(y))
   print(type(z))

Float datatype:

       Float datatype to represent floating-point value or decimal values, we can use a float datatype,
and it can use an exponential form also called scientific notation.
    
                                              exanple :       x = 1.10
y = 1.0
   z = -35.59

       print(type(x))
       print(type(y))
       print(type(z))

complex datatype:

          A complex datatype is a complex number is a number with a real and imaginary component
representing as a+bj where a and b are contain integer or float point value
          
                                                example :     x = 3+5j
y = 5j
 z = -5j

         print(type(x))
         print(type(y))
         print(type(z))

String datatype:  

           A string datatype is a sequence of characters enclosed within a single quotes or double quotes or triple single quotes or triple double quotes this character could be anything like letter, number or special character enclosed with quotes. 
          
               ------> A string is immutable that is it can't be changed once define

               ------>A string is in orderded we can perform in indexing and slicing



                 example :    
 
                     string_1 = 'this a string enclosed in single quotes.'
                      
                    string_2 = "this a string enclosed in double quotes."      
  
                    string_3 = '''this is multiple line 
                                       string, which has    
                                        lines in it enclosed in triple single quotes.'''

                    string_4 = """this is multiple line 
                                      string, which has    
                                      lines in it enclosed in triple single quotes."""


String can be indexing: 

          Positive indexing:

  • since strings are a sequence of chars, and this seq has an order. We can access individgual chars by their index or position in that seq enclose in [].

    x = 'python'

    string x has a len of 6, (len of string is equals to the number of chars in that string) the first index is 0 indexing in python starts with 0

                                                   example:
         a = "Hello, World!"
print(a[1])

      Negative indexing:

  • we can also access the chars in a string using reverse indexing.
  • reverse indexing starts at the end of the string, reverse indexing starts with -1
      
                              example:
                                a = "Hello, World!"
print(a[-2])


String can be slicing:  

  • as the word suggest, we can get a sub-string of the given string by performing slicing

  • to slice a string, we need three values: start_indexend_indexstep_size

    • start_index: from where the slicing has to start, or the starting index of sub-string.
    • end_index: in slicing, end index is end index - 1. end_index tells till which index the slicing has to happen, (we are not going to include char at end_index)
    • step_size: it talks about how many steps it has to move while performing the slicing. by default, step_size is +1
  • syntax for slicing:

    • var[start_index: end_index: step_size]

                        example:
   
        `                        b = "Hello, World"
                 print(b[2:5])
                                   print(b[2:])
                                   print(b[-5:-2])


String Concatenation:

To concatenate, or combine, two strings you can use the + operator.


              example:           
    
                       a = "Hello"                 a = "Hello"
           b = "World"                 b = "World"
           c = a + b                   c = a + " " + b
            print(c)                   print(c)           
           
             

String Methods

 center()          Returns a centered string
 count()     Returns the number of times a specified value occurs in a string
split()           Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value 
strip()         Returns a trimmed version of the string 
swapcase() Swaps cases, lower case becomes upper case and vice versa
 title()         Converts the first character of each word to upper case
 translate() Returns a translated string 
upper()         Converts a string into upper case
 zfill()         F string with a specified number of 0 values at the beginning
capitalize() Converts the first character to upper case 
casefold() Converts string into lower case
join()               Joins the elements of an iterable to the end of the string
 ljust()         Returns a left justified version of the string 
lower()         Converts a string into lower case
 lstrip()         Returns a left trim version of the string
 maketrans() Returns a translation table to be used in translations 
partition() Returns a tuple where the string is parted into three parts 
replace()         Returns a string where a specified value is replaced with a specified value
rjust()         Returns a right justified version of the string
 rpartition() Returns a tuple where the string is parted into three parts 
rsplit()         Splits the string at the specified separator, and returns a list 
rstrip()         Returns a right trim version of the string


List datatypes:

  Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are TupleSet, and Dictionary, all with different qualities and usage.


             example:

            thislist = ["apple""banana""cherry"]

                 print(thislist)


List Items

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.


Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.


Allow Duplicates

Since lists are indexed, lists can have items with the same value

        example:

    thislist = ["apple""banana""cherry""apple""cherry"]
     print(thislist)


List Length

To determine how many items a list has, use the len() function:

  example

      thislist = ["apple""banana""cherry"]
      print(len(thislist))


List Methods

 append()      Adds an element at the end of the list 

clear()      Removes all the elements from the list 

copy()      Returns a copy of the list 

count()      Returns the number of elements with the specified value

 extend()      Add the elements of a list (or any iterable), to the end of the current list 

index()       Returns the index of the first element with the specified value 

insert()       Adds an element at the specified position

 pop()       Removes the element at the specified position

 remove()       Removes the item with the specified value 

reverse()        Reverses the order of the list 

sort()         Sorts the list


Python Tuples


Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are ListSet, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and (unchangeable)immutable.

Tuples are written with round brackets.

                example:

                         x = ("apple""banana""cherry")

                   print(x)


Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.


Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.


Allow Duplicates

Since tuples are indexed, they can have items with the same value

                example:

                         x = ("apple""banana""cherry""apple""cherry")

              print(x)


To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

                example:

                                 x = ("apple",)

                print(type(x))

                x = ("apple")
                print(type(x))        #NOT a tuple
                

Python Sets

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are ListTuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unorderedunchangeable*, and unindexed.

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created.

Duplicates Not Allowed

Sets cannot have two items with the same value.

            example

            x = {"apple""banana""cherry""apple"}

        print(x)      #  Duplicate values will be ignored:

        x = {"apple""banana""cherry"True12}

        print(x)     

        print(len(x))

            print(type(x))


Python Dictionaries

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Dictionaries are written with curly brackets, and have keys and values.

      example:

                a = {'key_1':[1,2,3],

                        'key_2':(11,22,33),

                        'key_4':{111,333,222},

                        'key_5':'value_0',

                        'key_5':'value_0',

                        'key_6':{'key_1':[10,20,30],

                                     'key_2':(100,200,300),

                                     'key_4':{1000,2000,3000},

                                     'key_5':'value_5'}}

                 print(a)

                       print(len(a))

           print(type(a))

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.


Duplicates Not Allowed

Dictionaries cannot have two items with the same key:


Python Conditions and If statements

In Python, condition statements act depending on whether a given condition is true or false. You can execute different blocks of codes depending on the outcome of a condition. Condition statements always evaluate to either True or False.

          There are three types of conditional statements.

  1. if statement
  2. if-else
  3. if-elif-else
  4. nested if-else

If - else -elif-nested if statement in Python

In control statements, the if statement is the simplest form. It takes a condition and evaluates to either true or false

      Example: if statement            a = 33

                                       b = 200

                                       if b > a:

                                            print("b is greater than a")

        Example: if-elif               

                            a = 33
                            b = 33
                            if b > a:
                              print("b is greater than a")
                            elif a == b:
                              print("a and b are equal")

If the condition is true, the True block of code will be executed, and if the condition is False, then the block of code is skipped, and The controller moves to the next line

Example: if-elif-else

                        a = 200
                        b = 33
                        if b > a:
                          print("b is greater than a")
                        elif a == b:
                          print("a and b are equal")
                        else:

                          print("a is greater than b")               


Example:

                Q1) Write a Python program that takes an integer as input from the user and checks if the number is positive, negative, or zero.

x = int(input('Enter the value: '))

if x>0:             

    print('positive')

elif x<0:                               # elfi is used to check the condition when if is false

    print('negative')

else:                                    # else is the out of the statement when if is false

    print('zero')

OR

x = x = int(input('Enter the value: '))

if x>=0:                                    # if inside if is known as nested if

    if x==0:

        print('Zero')

    else:

        print('Positive')

else:

    print('Negative')


Comments