Day 12 - Introduction to Python

Day 12 - Introduction to Python

Introduction

Python is an interpreted, high-level, general-purpose programming language and was created by Guido Van Rossum in 1991.

Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including structured, object-oriented and functional programming.

An interpreter translates the command that you write out into code that the computer can understand.

Features

  1. It is simple and easy to understand.

  2. It is interpreted and platform-independent which makes debugging very easy.

  3. It is an open-source programming language.

  4. It is possible to integrated other programming languages with Python.

  5. It provides various libraries and frameworks support, like NumPy, OpenCV, Pandas, Django, Flask, Tensorflow, etc.

How to install Python

You can install Python in your System whether it is window, MacOS, ubuntu, centos etc. Below are the links for the installation:

Modules in Python

Modules are like a code library which can be used to borrow code written by somebody else in our Python program.

There are 2 types of Modules:

  1. Built-in Modules: These modules are ready to import and use as they come preinstalled with Python, there is no need to install such modules explicitly.

  2. User-defined Modules: These modules are the modules that you create yourself, or can be imported from a third party files or can be installed using package manager like "pip" or "conda".
    Since, the code is written by someone else, we can install different versions of a same module with time.

    pip: is a package manager used to install Python modules.

Data Types in Python

Data Types specifies the type of value a variable holds. A variable is like a container that holds data.

You can get the data type of any object by using the type() function.

input: a = 8 + 2j
        print(type(a))
output: The type of a is <class 'complex'>
input: b = "Smriti"
        print(type(b))
output: The type of b is <class 'str'>

So , here 'a' and 'b' are Variables.
          'complex' and 'str' are Data Types of 'a' and 'b' respectively.

By default, Python provides built-in data types:

  1. Numeric Data Types: Numeric data types in Python are used to represent numerical values. Python provides three primary numeric data types:

    • Integer (int): Integers are whole numbers without any decimal points. They can be positive or negative. Ex. : -3, 8, 0

    • Floating-Point (float): Floating-point numbers represent decimal values. They can be positive or negative and may contain a decimal point. Ex. : 0.001, 7.3245, -9.0

    • Complex (complex): Complex numbers are used to represent numbers with a real and imaginary part. They are written in the form of a + bj, where a is the real part and b is the imaginary part. Ex. : 8+2j

  2. String Data Type(str): Represents a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “), such as “Hello, World!”, ‘Python’.

  3. Boolean Data Type(bool): Represents either True or False, used for logical operations and conditions.

  4. Sequenced Data Types:

    • list: Represents an ordered and mutable collection of items separated by comma and enclosed within square brackets [ ].

        input: list=[8, mango, [-4,5], ["Rose", "Lily"]]
               print(list)
        output: [8, mango, [-4,5], ['Rose', 'Lily']]
      
    • tuple: Represents an ordered and immutable collection of items separated by comma and enclosed within parentheses ().

        input: tuple=(("parrot", "sparrow"),("lion", "tiger"))
               print(tuple)
        output: (('parrot', 'sparrow'), ('lion', 'tiger'))
      
  5. Mapped Data Type:

    dict: Represents an ordered collection of key-value pairs enclosed within curly braces {} with unique keys.

     input: dict={"name": "Smriti", "id" : "123"}
            print(dict)
     output: {'name': 'Smriti', 'id' : 123}
    
  6. Set Data Type:

    set: Represents an unordered and mutable collection of unique elements, enclosed in curly braces {} or using the set() function.

     input: set={2,4,6,2,3}
            print(set)
     output: {2,4,6,3}
    

Print Statement in Python

The print() function prints the specified message to the screen, or other standard output device.

The message can be a string, or any other object, the object will be converted into a string before written to the screen.

Syntax: print(object(s), sep=separator, end=end, file=file, flush=flush)
Where, object(s): Any object. Will be converted to string before printed.
       sep='separator': Optional. Specify how to separate the objects, if there is more than one. Default is ' '.
       end='end': Optional. Specify what to print at the end. Default is '\n' (line feed).
       file: Optional. An object with a write method. Default is sys.stdout
       flush: Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False

Example :

i/p: print("Hey", 6, 7, sep="~")
o/p: Hey~6~7

i/p: print("Hey", 6, 7, sep="~",end="003")
o/p: Hey~6~7003

Comments in Python

Comments are the part of the coding file that the programmer does not want to execute, rather programmer uses it to either explain the block of code or to avoid the execution of a specific part of code while testing.

Comments in Python are identified with a hash symbol, #, and extend to the end of the line.

There are 2 ways to give comment in your coding file:

  1. Single-line Comment: Single-line comments begin with the “#” character. Anything that is written in a single line after ‘#’ is considered as a comment.

     # This is a single line comment.
    
  2. Multi-Line Comments: Python does not support multi-line comments. However, there are multiple ways to overcome this issue. None of these ways are technically multi-line comments, but you can use them as one.

    The first way is by using # at the beginning of each line of the comment.

     #This is
     #a
     #multi-line comment
    

    The next way is by using string literals. You can either use a single (‘’) quotation or double (“”) quotation.

     """
     This is a 
     multi-line
     comment
     """
     OR
     '''
     This is
     also a
     multi-line
     comment
     '''
    

Escape Sequence in Python

We use "Escape Sequence" to insert character that cannot be directly used in a string.

An Escape Sequence is a backslash(\) character followed by the character we want to insert.

i/p: print("This is an\nescape sequence")
o/p: This is an
     escape sequence
\n -> new line character

i/p: print("Hi! My name is \"Smriti Sharma\"")
o/p: Hi! My name is "Smriti Sharma"
\" -> To insert " character

Typecasting in Python

The conversion of one data type to other data type in order to perform the required operation by users is known as typecasting.

Python provides a varieties of functions or methods like int(), str(), float() etc.

There are 2 types of typecasting:

  1. Implicit Typecasting: Data Types in Python do not have the same level, that means ordering of data types is not the same.
    While performing any operations on variables with different data types, one of the variable's data type will be changed to the higher data type automatically.

     i/p: a=7
          print(type(a))
          b=3.0
          print(type(b))
          c=a+b
          print(c)
          print(type(c))
     o/p: <class 'int'>
          <class 'float'>
          10.0
          <class 'float'>
    
  2. Explicit Typecasting: The conversion of data type into another data type, done via developer or programmer's intervention or manually as per the requirement.

    It can be achieved with the help of Python's built-in type conversion function such as int(), float(), etc.

     i/p: String="15"
          number=7
          string_number=int(String)
          sum=number+string_number
          print("The sum is: ",sum)
     o/p: The sum is 22
    

Conclusion

In conclusion, Python is a versatile and powerful programming language widely used for various applications, from web development to data analysis and machine learning. One of its strengths lies in its dynamic typing system, allowing developers to create code more efficiently and with less verbosity.

Python supports a variety of built-in data types, such as integers, floats, strings, lists, tuples, and dictionaries, providing flexibility for different programming tasks.

Typecasting, the process of converting one data type to another, is straightforward in Python, thanks to its dynamic nature. Developers can easily switch between data types using functions like int(), float(), str(), and others.

Overall, Python's simplicity, readability, and extensive library support contribute to its popularity and widespread adoption in the software development community.

👆The information presented above is based on my interpretation. Suggestions are always welcome.😊

~Smriti Sharma✌