Python Features

Python is a feature-rich and versatile language, it is highly capable, high-level, interpreted, interactive, and object-oriented language. in this tutorial, we will explore some important key features of Python.


◆ User-Friendly Syntax
◆ Interpreter language
◆ Extending and Embedding Nature:
◆ DataBases Connectivity 
◆ Cross Platform Compatibility 
◆ Object Oriented 


User-Friendly Syntax:

Reading Python code feels like reading English syntax, it's possible because of mainly 4 main reasons.

1. Limited set of keywords: 

Python has a limited set of keywords, which is nothing but like "English words" that you can see by importing the keyword module and you need not remember all, by using it in your day-to-day you will be familiar with each of them.
You can directly access all keywords by importing the keyword module. 


After running this code you will get the output of all built-in Python keywords.

Output: 
False, None, True, and, as, assert, async, await, break, class, continue, def, del, Elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
 
These are also called reserved words that have specific meanings in Python, so you can not use these words for another purpose. We will explore all of these in the letter chapter.

2. Use of indentations: 

Unlike other languages, python does not use curly braces {} to organize code, it uses basically "spaces" or "tabs" at the beginning of the line which is referred to as indentation in Python.

In Python : 


In C language :


Here we can see now C language uses curly braces {} to organise code while Python just being okay with space which is known as an indentation in Python.

Key Rules:
◆ Use a consistent number of spaces or tabs for indentation (4 spaces is a common convention).
◆ Indent code blocks after certain keywords like if, for, while, def, class, etc.
◆ Dedent (decrease indentation) to indicate the end of a block it's the reverse of indentation.

Noteyou can specify tab size in your code editor setting or keyword setting.
ExampleSet 1 tab button press would be 2 space button press or 1 tab button press equal to 4 space button press

Benefits of Indentation in Python:
◆ Readability: Indentation makes code easier to read and understand by visually grouping related statements.
◆ Structure: Enforces a clear structure and hierarchy within the code.
◆ Error Prevention: Helps prevent syntax errors by making block boundaries explicit.

Best Practices:
◆ Use one indentation style either spaces or tabs, but not both.
◆ Use a linter or code formatted to automatically check and correct indentation, many code editors offer extensions for dynamic indentation checking.
◆ Visually check indentation levels when reviewing or debugging your code.

3. Use of line breaks: 

Python uses line breaks to end commands but other languages like Java or C/C++  use semicolons, extra parenthesis or any other specific character like C uses " \n" for line breaks(line changing)

Python :

# Python example
print("This is a Python statement.")
print("Statements are separated by line breaks.")

Here you can see we simply changed the line just simple pressing enter There is no semicolons or extra parenthesis required.

Java language:
// Java example
public class Example {
    public static void main(String[] args) {
        System.out.println("This is a Java statement.");
        System.out.println("Statements are separated by line breaks.");
    }
}
Here In the above code, Java used semicolons for changing the line. 

C language:

#include <stdio.h>

int main() {

    printf("This is a C statement.\n");

    printf("Statements are separated by line breaks.\n");

    return 0;}

In this above code, C has used \n for changing the line. 

4. Dynamic type checking:

Python has a dynamic type-checking system, which means a Python interpreter can change the 'type' of variables during runtime. There is no need to you define data type explicitly. they are determined at runtime based on the value assigned to them.

x = 5      # x is an integer
x = "hello"  # x is now a string
x = [1, 2, 3]  # x is now a list 
 
In this example, the variable x starts as an integer, then becomes a string, and finally a list. This dynamic type checking is one of the characteristics of Python's flexibility.
It's not limited to just variables but also new classes and objects that can be created and modified during runtime.

Note: there could be runtime errors if the variable is not used properly.
For example :
x = 5
y = "hello"
z = x + y  # This will result in a TypeError
 
because x is an integer and y is a string so you can't perform add operation between a string and an integer.
while in statically- typed languages like Java, C++, and Swift the data type of the variable must be declared explicitly at the time of compilation, and once a variable is assigned a certain type, its type becomes fixed and cannot be changed during the execution of code.

Interpreter language:

In any programming language, your source code must be in a machine-readable format, known as binary code (0 or 1), before it gets executed. This is what a computer can essentially understand. A programming language can be either compiled or interpreted based.

In a compiled language, your source code is translated all at once into machine code before execution. However, if there's even a small error in your source code statement, the translation gets interrupted and fails. To identify errors, you have to go through all your source code, making development less efficient for coders trying to get things done. There are plenty of compiled languages; here are some of them: C, C++, Java, C#, Swift, Rust, Go (Golang), and Kotlin.

On the other hand, In an interpreted language, your source code is executed line by line and translated into machine code as it goes. the execution of instructions continues until an error is encountered in your source code. if there's an error in your code statement, the interpreter interrupts the process on the spot and throws an error. this unique feature makes debugging easier, allowing you to pinpoint exactly where a statement in your code is incorrect. It is particularly beneficial for new programmers who can gradually build confidence. this is why Python stands out as a beginner-friendly language.

Extending and Embedding Nature:

Although Python has a lot of features, as humans, we always tend to do more so Python provides features to easily add, modify, or extend its functionality like functions, objects, methods, and data types implemented in C or C++ (or other languages that are callable from C language like Java, Pascal, C++...).

That's the main reason Python software is distributed with a standard library made of a large number of modules and packages.

For example: for faster computation python has a library called Numpy, which is written in C and Python combined, that's written by developers to give extra power to Python by adding extra functionality and classes like "numpy.ndarray" and hosted over GitHub for everyone's use.

And same as Pandas library which is also very popular for data analysis is built on top of numpy and written in C and Cython which gives more functionality to Python by adding classes like pandas.series and pandas.dataframe and methods that are hosted over Github for everyone's use.

Now hope you can understand the power of these Python features, numerous libraries in the PyData ecosystem are written by some great folks to make our lives easy.

Note: CPython a default and most widely used implementation of the Python programming language, is also written in C. we will letter discuss more about it.

DataBases Connectivity:

python offers many libraries and modules to establish connections with databases, you can connect almost all major popular database management systems in your server-side Python application for connecting to databases.

DB-API is a set of rules that defines how Python talks to relational databases through database driver software.
Here are some popular options for database connections in Python:

SQLite3:
SQLite is a popular lightweight, serverless database engine that comes preinstalled with Python and some OS like Mac has already been installed.

 The SQLite3 module from Python allows Python programs to interact with SQLite databases...

import sqlite3

# Connect to a SQLite database (creates a new one if not exists)
connection = sqlite3.connect('example.db')

# Perform database operations

# Close the connection when done
connection.close() 

2. MySQL:

For MySQL databases, you can use the mysql-connector or pymysql libraries.

import mysql.connector
# Connect to a MySQL database
connection = mysql.connector.connect(
    host='localhost',
    user='username',
    password='password',
    database='database_name'
)
# Perform database operations 
# Close the connection when done
connection.close()

 

3PostgreSQL:

To connect with PostgreSQL databases, python offer the psycopg2 library.

import psycopg2

# Connect to a PostgreSQL database

connection = psycopg2.connect(

    host='localhost',

    user='username',

    password='password',

    database='database_name')

# Perform database operations

# Close the connection when done

connection.close()

if you are more curious to know I have written a whole thread here 


Cross Platform Compatibility:

Unlike other languages, you don't need to set up different environment systems or run specific commands to execute Python code. Python is a cross-platform language, meaning it can work on different operating systems like Windows, Linux, Mac OS, and Android OS. The main version of Python, called CPython, is written in C. and also is the default implementation of Python, and the best part is it's all completely available free to download the source code of Python and their precompiled binaries for various operating system platforms.

When you write a Python program, it first gets compiled into an intermediate platform-independent byte code. The interpreter's virtual machine then executes this byte code. This characteristic makes Python cross-platform, allowing easy porting of Python programs from one operating system to another operating system.



Post a Comment

Previous Post Next Post