Author: Saim Khalid

  • Python Variables

    A variable is the name given to a memory location. A value-holding Python variable is also known as an identifier.

    Since Python is an infer language that is smart enough to determine the type of a variable, we do not need to specify its type in Python.

    Variable names must begin with a letter or an underscore, but they can be a group of both letters and digits.

    The name of the variable should be written in lowercase. Both Rahul and rahul are distinct variables.

    Identifier Naming

    Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the program. The standards to name an identifier are given underneath.

    • The variable’s first character must be an underscore or alphabet (_).
    • Every one of the characters with the exception of the main person might be a letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
    • White space and special characters (!, @, #, %, etc.) are not allowed in the identifier name. ^, &, *).
    • Identifier name should not be like any watchword characterized in the language.
    • Names of identifiers are case-sensitive; for instance, my name, and MyName isn’t something very similar.
    • Examples of valid identifiers: a123, _n, n_9, etc.
    • Examples of invalid identifiers: 1a, n%4, n 9, etc.

    Declaring Variable and Assigning Values

    • Python doesn’t tie us to pronounce a variable prior to involving it in the application. It permits us to make a variable at the necessary time.
    • In Python, we don’t have to explicitly declare variables. The variable is declared automatically whenever a value is added to it.
    • The equal (=) operator is utilized to assign worth to a variable.

    Object References

    When we declare a variable, it is necessary to comprehend how the Python interpreter works. Compared to a lot of other programming languages, the procedure for dealing with variables is a little different.

    Python is the exceptionally object-arranged programming language; Because of this, every data item is a part of a particular class. Think about the accompanying model.

    print("John")  

    Output:John

    The Python object makes a integer object and shows it to the control center. We have created a string object in the print statement above. Make use of the built-in type() function in Python to determine its type.

    type("John")  

    Output:<class ‘str’>

    In Python, factors are an symbolic name that is a reference or pointer to an item. The factors are utilized to indicate objects by that name.

    Let’s understand the following example

    a = 50   

    Python Variables

    In the above image, the variable a refers to an integer object.

    Suppose we assign the integer value 50 to a new variable b.

    a = 50  
    
    b = a
    Python Variables

    The variable b refers to the same object that a points to because Python does not create another object.

    Let’s assign the new value to b. Now both variables will refer to the different objects.

    a = 50  
    
    b =100
    Python Variables

    Python manages memory efficiently if we assign the same variable to two different values.

    Object Identity

    Every object created in Python has a unique identifier. Python gives the dependable that no two items will have a similar identifier. The object identifier is identified using the built-in id() function. consider about the accompanying model.

    a = 50  
    
    b = a  
    
    print(id(a))  
    
    print(id(b))  
    
    # Reassigned variable a  
    
    a = 500  
    
    print(id(a))

    Output:140734982691168 140734982691168 2822056960944

    We assigned the b = a, an and b both highlight a similar item. The id() function that we used to check returned the same number. We reassign a to 500; The new object identifier was then mentioned.

    Variable Names

    The process for declaring the valid variable has already been discussed. Variable names can be any length can have capitalized, lowercase (start to finish, a to z), the digit (0-9), and highlight character(_). Take a look at the names of valid variables in the following example.

    name = "Devansh"  
    
    age = 20  
    
    marks = 80.50  
    
      
    
    print(name)  
    
    print(age)  
    
    print(marks)

    Output:Devansh 20 80.5

    Consider the following valid variables name.

    name = "A"  
    
    Name = "B"  
    
    naMe = "C"  
    
    NAME = "D"  
    
    n_a_m_e = "E"  
    
    _name = "F"  
    
    name_ = "G"  
    
    _name_ = "H"  
    
    na56me = "I"  
    
      
    
    print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)

    Output:A B C D E D E F G F I

    We have declared a few valid variable names in the preceding example, such as name, _name_, and so on. However, this is not recommended because it may cause confusion when we attempt to read code. To make the code easier to read, the name of the variable ought to be descriptive.

    The multi-word keywords can be created by the following method.

    • Camel Case – In the camel case, each word or abbreviation in the middle of begins with a capital letter. There is no intervention of whitespace. For example – nameOfStudent, valueOfVaraible, etc.
    • Pascal Case – It is the same as the Camel Case, but here the first word is also capital. For example – NameOfStudent, etc.
    • Snake Case – In the snake case, Words are separated by the underscore. For example – name_of_student, etc.

    Multiple Assignment

    Multiple assignments, also known as assigning values to multiple variables in a single statement, is a feature of Python.

    We can apply different tasks in two ways, either by relegating a solitary worth to various factors or doling out numerous qualities to different factors. Take a look at the following example.

    1. Assigning single value to multiple variables

    Eg:

    x=y=z=50    
    
    print(x)    
    
    print(y)    
    
    print(z)

    Output:50 50 50

    2. Assigning multiple values to multiple variables:

    Eg:

    a,b,c=5,10,15    
    
    print a    
    
    print b    
    
    print c

    Output:5 10 15

    The values will be assigned in the order in which variables appear.

    Python Variable Types

    There are two types of variables in Python – Local variable and Global variable. Let’s understand the following variables.

    Local Variable

    The variables that are declared within the function and have scope within the function are known as local variables. Let’s examine the following illustration.

    Example –

    # Declaring a function  
    
    def add():  
    
        # Defining local variables. They has scope only within a function  
    
        a = 20  
    
        b = 30  
    
        c = a + b  
    
        print("The sum is:", c)  
    
      
    
    # Calling a function  
    
    add()

    Output:The sum is: 50

    Explanation:

    We declared the function add() and assigned a few variables to it in the code above. These factors will be alluded to as the neighborhood factors which have scope just inside the capability. We get the error that follows if we attempt to use them outside of the function.

    add()  
    
    # Accessing local variable outside the function   
    
    print(a)

    Output:The sum is: 50 print(a) NameError: name ‘a’ is not defined

    We tried to use local variable outside their scope; it threw the NameError.

    Global Variables

    Global variables can be utilized all through the program, and its extension is in the whole program. Global variables can be used inside or outside the function.

    By default, a variable declared outside of the function serves as the global variable. Python gives the worldwide catchphrase to utilize worldwide variable inside the capability. The function treats it as a local variable if we don’t use the global keyword. Let’s examine the following illustration.

    Example –

    # Declare a variable and initialize it  
    
    x = 101  
    
      
    
    # Global variable in function  
    
    def mainFunction():  
    
        # printing a global variable  
    
        global x  
    
        print(x)  
    
        # modifying a global variable  
    
        x = 'Welcome To Javatpoint'  
    
        print(x)  
    
      
    
    mainFunction()  
    
    print(x)

    Output:101 Welcome To Javatpoint Welcome To Javatpoint

    Explanation:

    In the above code, we declare a global variable x and give out a value to it. We then created a function and used the global keyword to access the declared variable within the function. We can now alter its value. After that, we gave the variable x a new string value and then called the function and printed x, which displayed the new value.=

    Delete a variable

    We can delete the variable using the del keyword. The syntax is given below.

    Syntax –

    del <variable_name>  

    In the following example, we create a variable x and assign value to it. We deleted variable x, and print it, we get the error “variable x is not defined”. The variable x will no longer use in future.

    Example –

    # Assigning a value to x  
    
    x = 6  
    
    print(x)  
    
    # deleting a variable.   
    
    del x  
    
    print(x)

    Output:6 Traceback (most recent call last): File “C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py”, line 389, in print(x) NameError: name ‘x’ is not defined

    Maximum Possible Value of an Integer in Python

    Python, to the other programming languages, does not support long int or float data types. It uses the int data type to handle all integer values. The query arises here. In Python, what is the maximum value that the variable can hold? Take a look at the following example.

    Example –

    
    
    1. # A Python program to display that we can store  
    2. # large numbers in Python  
    3.   
    4. a = 10000000000000000000000000000000000000000000  
    5. a = a + 1  
    6. print(type(a))  
    7. print (a)  

    Output:<class ‘int’> 10000000000000000000000000000000000000000001

    As we can find in the above model, we assigned a large whole number worth to variable x and really look at its sort. It printed class <int> not long int. As a result, the number of bits is not limited, and we are free to use all of our memory.

    There is no special data type for storing larger numbers in Python.

    Print Single and Numerous Factors in Python

    We can print numerous factors inside the single print explanation. The examples of single and multiple printing values are provided below.

    Example – 1 (Printing Single Variable)

    # printing single value   
    
    a = 5  
    
    print(a)  
    
    print((a))

    Output:5 5

    Example – 2 (Printing Multiple Variables)

    
    
    1. a = 5  
    2. b = 6  
    3. # printing multiple variables  
    4. print(a,b)  
    5. # separate the variables by the comma  
    6. Print(1, 2, 3, 4, 5, 6, 7, 8) 

    Output:5 6 1 2 3 4 5 6 7 8

    Basic Fundamentals:

    This section contains the fundamentals of Python, such as:

    i)Tokens and their types.

    ii) Comments

    a)Tokens:

    • The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
    • The token is the smallest unit inside the given program.

    There are following tokens in Python:

    • Keywords.
    • Identifiers.
    • Literals.
    • Operators.
  • First Python Program

    In this Section, we will discuss the basic syntax of Python, we will run a simple program to print Hello World on the console.

    Python provides us the two ways to run a program:

    • Using Interactive interpreter prompt
    • Using a script file

    Let’s discuss each one of them in detail.

    Interactive interpreter prompt

    Python provides us the feature to execute the Python statement one by one at the interactive prompt. It is preferable in the case where we are concerned about the output of each line of our Python program.

    To open the interactive mode, open the terminal (or command prompt) and type python (python3 in case if you have Python2 and Python3 both installed on your system).

    It will open the following prompt where we can execute the Python statement and check their impact on the console.

    First Python Program

    After writing the print statement, press the Enter key.

    First Python Program

    Here, we get the message “Hello World !” printed on the console.

    Using a script file (Script Mode Programming)

    The interpreter prompt is best to run the single-line statements of the code. However, we cannot write the code every-time on the terminal. It is not suitable to write multiple lines of code.

    Using the script mode, we can write multiple lines code into a file which can be executed later. For this purpose, we need to open an editor like notepad, create a file named and save it with .py extension, which stands for “Python”. Now, we will implement the above example using the script mode.

    1. print (“hello world”); #here, we have used print() function to print the message on the console.    

    To run this file named as first.py, we need to run the following command on the terminal.

    First Python Program

    Step – 1: Open the Python interactive shell, and click “File” then choose “New”, it will open a new blank script in which we can write our code.

    First Python Program

    Step -2: Now, write the code and press “Ctrl+S” to save the file.

    First Python Program

    Step – 3: After saving the code, we can run it by clicking “Run” or “Run Module”. It will display the output to the shell.

    First Python Program

    The output will be shown as follows.

    First Python Program

    Step – 4: Apart from that, we can also run the file using the operating system terminal. But, we should be aware of the path of the directory where we have saved our file.

    • Open the command line prompt and navigate to the directory.
    First Python Program
    • We need to type the python keyword, followed by the file name and hit enter to run the Python file.
    First Python Program

    Multi-line Statements

    Multi-line statements are written into the notepad like an editor and saved it with .py extension. In the following example, we have defined the execution of the multiple code lines using the Python script.

    Code:

    1. name = “Andrew Venis”  
    2. branch = “Computer Science”  
    3. age = “25”  
    4. print(“My name is: “, name, )  
    5. print(“My age is: “, age)  

    Script File:

    First Python Program
    First Python Program

    Pros and Cons of Script Mode

    The script mode has few advantages and disadvantages as well. Let’s understand the following advantages of running code in script mode.

    • We can run multiple lines of code.
    • Debugging is easy in script mode.
    • It is appropriate for beginners and also for experts.

    Let’s see the disadvantages of the script mode.

    • We have to save the code every time if we make any change in the code.
    • It can be tedious when we run a single or a few lines of code.

    Get Started with PyCharm

    In our first program, we have used gedit on our CentOS as an editor. On Windows, we have an alternative like notepad or notepad++ to edit the code. However, these editors are not used as IDE for python since they are unable to show the syntax related suggestions.

    JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run the python programs.

    PyCharm installation

    As we have already stated, PyCharm is a cross-platform IDE, and hence it can be installed on a variety of the operating systems. In this section of the tutorial, we will cover the installation process of PyCharm on Windows, MacOSCentOS, and Ubuntu.

    Windows

    Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating system, visit the link https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows to download the executable installer. Double click the installer (.exe) file and install PyCharm by clicking next at each step.

    To create a first program to Pycharm follows the following step.

    Step – 1. Open Pycharm editor. Click on “Create New Project” option to create new project.

    First Python Program

    Step – 2. Select a location to save the project.

    1. We can save the newly created project at desired memory location or can keep file location as it is but atleast change the project default name untitled to “FirstProject” or something meaningful.
    2. Pycharm automatically found the installed Python interpreter.
    3. After change the name click on the “Create” Button.
    First Python Program

    Step – 3. Click on “File” menu and select “New”. By clicking “New” option it will show various file formats. Select the “Python File”.

    First Python Program

    Step – 4. Now type the name of the Python file and click on “OK”. We have written the “FirstProgram”.

    First Python Program

    Step – 5. Now type the first program – print(“Hello World”) then click on the “Run” menu to run program.

    First Python Program

    Step – 6. The output will appear at the bottom of the screen.

    First Python Program

    Basic Syntax of Python

    Indentation and Comment in Python

    Indentation is the most significant concept of the Python programming language. Improper use of indentation will end up “IndentationError” in our code.

    Indentation is nothing but adding whitespaces before the statement when it is needed. Without indentation Python doesn’t know which statement to be executed to next. Indentation also defines which statements belong to which block. If there is no indentation or improper indentation, it will display “IndentationError” and interrupt our code.

    First Python Program

    Python indentation defines the particular group of statements belongs to the particular block. The programming languages such as CC++java use the curly braces {} to define code blocks.

    In Python, statements that are the same level to the right belong to the same block. We can use four whitespaces to define indentation. Let’s see the following lines of code.

    Example –

    list1 = [1, 2, 3, 4, 5]  
    
    for i in list1:  
    
        print(i)  
    
        if i==4:  
    
           break  
    
    print("End of for loop")

    Output:1 2 3 4 End of for loop

    Explanation:

    In the above code, for loop has a code blocks and if the statement has its code block inside for loop. Both indented with four whitespaces. The last print() statement is not indented; that’s means it doesn’t belong to for loop.

    Comments in Python

    Comments are essential for defining the code and help us and other to understand the code. By looking the comment, we can easily understand the intention of every line that we have written in code. We can also find the error very easily, fix them, and use in other applications.

    In Python, we can apply comments using the # hash character. The Python interpreter entirely ignores the lines followed by a hash character. A good programmer always uses the comments to make code under stable. Let’s see the following example of a comment.

    1. name  = “Thomas”   # Assigning string value to the name variable   

    We can add comment in each line of the Python code.

    Fees = 10000      # defining course fees is 10000  
    
    Fees = 20000      # defining course fees is 20000

    It is good idea to add code in any line of the code section of code whose purpose is not obvious. This is a best practice to learn while doing the coding.

    Types of Comment

    Python provides the facility to write comments in two ways- single line comment and multi-line comment.

    Single-Line Comment – Single-Line comment starts with the hash # character followed by text for further explanation.

    # defining the marks of a student   
    
    Marks = 90

    We can also write a comment next to a code statement. Consider the following example.

    Name = "James"   # the name of a student is James  
    
    Marks = 90            # defining student's marks  
    
    Branch = "Computer Science"   # defining student branch

    Multi-Line Comments – Python doesn’t have explicit support for multi-line comments but we can use hash # character to the multiple lines. For example –

    # we are defining for loop  
    
    # To iterate the given list.  
    
    # run this code.

    We can also use another way.

    " " "   
    
    This is an example  
    
    Of multi-line comment  
    
    Using triple-quotes   
    
    " " "

    This is the basic introduction of the comments. Visit our Python Comment tutorial to learn it in detail.

    Python Identifiers

    Python identifiers refer to a name used to identify a variable, function, module, class, module or other objects. There are few rules to follow while naming the Python Variable.

    • A variable name must start with either an English letter or underscore (_).
    • A variable name cannot start with the number.
    • Special characters are not allowed in the variable name.
    • The variable’s name is case sensitive.

    Let’s understand the following example.

    Example –

    number = 10  
    
    print(num)  
    
      
    
    _a = 100  
    
    print(_a)  
    
      
    
    x_y = 1000  
    
    print(x_y)

    Output:10 100 1000

    We have defined the basic syntax of the Python programming language. We must be familiar with the core concept of any programming languages. Once we memorize the concepts as mentioned above. The journey of learning Python will become easier.

  • How to Install Python

    Python is a popular high-level, general-use programming language. Python is a programming language that enables rapid development as well as more effective system integration. Python has two main different versions: Python 2 and Python 3. Both are really different.

    Python develops new versions with changes periodically and releases them according to version numbers. Python is currently at version 3.11.3.

    Python is much simpler to learn and programme in. Any plain text editor, such as notepad or notepad++, may be used to create Python programs. To make it easier to create these routines, one may also utilise an online IDE for Python or even install one on their machine. IDEs offer a variety of tools including a user-friendly code editor, the debugger, compiler, etc.

    One has to have Python installed on their system in order to start creating Python code and carrying out many fascinating and helpful procedures. The first step in learning how to programming in Python is to install or update Python on your computer. There are several ways to install Python: you may use a package manager, get official versions from Python.org, or install specialised versions for embedded devices, scientific computing, and the Internet of Things.

    In order to become Python developer, the first step is to learn how to install or update Python on a local machine or computer. In this tutorial, we will discuss the installation of Python on various operating systems.

    Installation on Windows

    Visit the link https://www.python.org to download the latest release of Python. In this process, we will install Python 3.11.3 on our Windows operating system. When we click on the above link, it will bring us the following page.

    Python Environment Set-up

    Step – 1: Select the Python’s version to download.

    Click on the download button to download the exe file of Python.

    Python Environment Set-up

    If in case you want to download the specific version of Python. Then, you can scroll down further below to see different versions from 2 and 3 respectively. Click on download button right next to the version number you want to download.

    Python Environment Set-up

    Step – 2: Click on the Install Now

    Double-click the executable file, which is downloaded.

    Python Environment Set-up

    The following window will open. Click on the Add Path check box, it will set the Python path automatically.

    Now, Select Customize installation and proceed. We can also click on the customize installation to choose desired location and features. Other important thing is install launcher for the all user must be checked.

    Here, under the advanced options, click on the checkboxes of ” Install Python 3.11 for all users “, which is previously not checked in. This will checks the other option ” Precompile standard library ” automatically. And the location of the installation will also be changed. We can change it later, so we leave the install location default. Then, click on the install button to finally install.

    Python Environment Set-up

    Step – 3 Installation in Process

    Python Environment Set-up

    The set up is in progress. All the python libraries, packages, and other python default files will be installed in our system. Once the installation is successful, the following page will appear saying ” Setup was successful “.

    Python Environment Set-up

    Step – 4: Verifying the Python Installation

    To verify whether the python is installed or not in our system, we have to do the following.

    • Go to “Start” button, and search ” cmd “.
    • Then type, ” python – – version “.
    • If python is successfully installed, then we can see the version of the python installed.
    • If not installed, then it will print the error as ” ‘python’ is not recognized as an internal or external command, operable program or batch file. “.
    Python Environment Set-up

    We are ready to work with the Python.

    Step – 5: Opening idle

    Now, to work on our first python program, we will go the interactive interpreter prompt(idle). To open this, go to “Start” and type idle. Then, click on open to start working on idle.

    Python Environment Set-up
  • Python Applications

    Python is known for its general-purpose nature that makes it applicable in almost every domain of software development. Python makes its presence in every emerging field. It is the fastest-growing programming language and can develop any application.

    Here, we are specifying application areas where Python can be applied.

    Python Applications

    1) Web Applications

    We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used on Instagram. Python provides many useful frameworks, and these are given below:

    • Django and Pyramid framework(Use for heavy applications)
    • Flask and Bottle (Micro-framework)
    • Plone and Django CMS (Advance Content management)

    2) Desktop GUI Applications

    The GUI stands for the Graphical User Interface, which provides a smooth interaction to any application. Python provides a Tk GUI library to develop a user interface. Some popular GUI libraries are given below.

    • Tkinter or Tk
    • wxWidgetM
    • Kivy (used for writing multitouch applications )
    • PyQt or Pyside

    3) Console-based Application

    Console-based applications run from the command-line or shell. These applications are computer program which are used commands to execute. This kind of application was more popular in the old generation of computers. Python can develop this kind of application very effectively. It is famous for having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for the command-line applications.

    Python provides many free library or module which helps to build the command-line apps. The necessary IO libraries are used to read and write. It helps to parse argument and create console help text out-of-the-box. There are also advance libraries that can develop independent console apps.

    4) Software Development

    Python is useful for the software development process. It works as a support language and can be used to build control and management, testing, etc.

    • SCons is used to build control.
    • Buildbot and Apache Gumps are used for automated continuous compilation and testing.
    • Round or Trac for bug tracking and project management.

    5) Scientific and Numeric

    This is the era of Artificial intelligence where the machine can perform the task the same as the human. Python language is the most suitable language for Artificial intelligence or machine learning. It consists of many scientific and mathematical libraries, which makes easy to solve complex calculations.

    Implementing machine learning algorithms require complex mathematical calculation. Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc. If you have some basic knowledge of Python, you need to import libraries on the top of the code. Few popular frameworks of machine libraries are given below.

    • SciPy
    • Scikit-learn
    • NumPy
    • Pandas
    • Matplotlib

    6) Business Applications

    Business Applications differ from standard applications. E-commerce and ERP are an example of a business application. This kind of application requires extensively, scalability and readability, and Python provides all these features.

    Oddo is an example of the all-in-one Python-based application which offers a range of business applications. Python provides a Tryton platform which is used to develop the business application.

    7) Audio or Video-based Applications

    Python is flexible to perform multiple tasks and can be used to create multimedia applications. Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The few multimedia libraries are given below.

    • Gstreamer
    • Pyglet
    • QT Phonon

    8) 3D CAD Applications

    The CAD (Computer-aided design) is used to design engineering related architecture. It is used to develop the 3D representation of a part of a system. Python can create a 3D CAD application by using the following functionalities.

    • Fandango (Popular )
    • CAMVOX
    • HeeksCNC
    • AnyCAD
    • RCAM

    9) Enterprise Applications

    Python can be used to create applications that can be used within an Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.

    10) Image Processing Application

    Python contains many libraries that are used to work with the image. The image can be manipulated according to our requirements. Some libraries of image processing are given below.

    • OpenCV
    • Pillow
    • SimpleITK

    In this topic, we have described all types of applications where Python plays an essential role in the development of these applications. In the next tutorial, we will learn more concepts about Python.

  • Python History and Versions

    • Python laid its foundation in the late 1980s.
    • The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in Netherland.
    • In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources.
    • In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
    • Python 2.0 added new features such as list comprehensions, garbage collection systems.
    • On December 3, 2008, Python 3.0 (also called “Py3K”) was released. It was designed to rectify the fundamental flaw of the language.
    • ABC programming language is said to be the predecessor of Python language, which was capable of Exception Handling and interfacing with the Amoeba Operating System.
    • The following programming languages influence Python:
      • ABC language.
      • Modula-3
    • Why the Name Python?
    • There is a fact behind choosing the name PythonGuido van Rossum was reading the script of a popular BBC comedy series “Monty Python’s Flying Circus“. It was late on-air 1970s.
    • Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select naming Python after the “Monty Python’s Flying Circus” for their newly created programming language.
    • The comedy series was creative and well random. It talks about everything. Thus it is slow and unpredictable, which made it very interesting.
    • Python is also versatile and widely used in every technical field, such as Machine LearningArtificial Intelligence, Web Development, Mobile Application, Desktop Application, Scientific Calculation, etc.
    • Python Version List
    • Python programming language is being updated regularly with new features and supports. There are lots of update in Python versions, started from 1994 to current release.
    • A list of Python versions with its released date is given below.
    • Tips to Keep in Mind While Learning Python
    • The most common question asked by the beginners – “What is the best way to learn Python”? It is the initial and relevant question because first step in learning any programming language is to know how to learn.
    • The proper way of learning will help us to learn fast and become a good Python developer.
    • In this section, we will discuss various tips that we should keep in mind while learning Python.
    • 1. Make it Clear Why We Want to Learn
    • The goal should be clear before learning the Python. Python is an easy, a vast language as well. It includes numbers of libraries, modules, in-built functions and data structures. If the goal is unclear then it will be a boring and monotonous journey of learning Python. Without any clear goal, you perhaps won’t make it done.
    • So, first figure out the motivation behind learning, which can anything be such as knowing something new, develop projects using Python, switch to Python, etc. Below are the general areas where Python is widely used. Pick any of them.
    • Data Analysis and Processing
    • Artificial Intelligence
    • Games
    • Hardware/Sensor/Robots
    • Desktop Applications
    • Choose any one or two areas according to your interest and start the journey towards learning Python.
    • 2. Learn the Basic Syntax
    • It is the most essential and basic step to learn the syntax of the Python programming language. We have to learn the basic syntax before dive deeper into learning it. As we have discussed in our earlier tutorial, Python is easy to learn and has a simple syntax. It doesn’t use semicolon and brackets. Its syntax is like the English language.
    • So it will take minimum amount of time to learning its syntax. Once we get its syntax properly, further learning will be easier and quicker getting to work on projects.
    • Note – Learn Python 3, not Python 2.7, because the industry no longer uses it. Our Python tutorial is based on its latest version Python 3.
    • 3. Write Code by Own
    • Writing the code is the most effective and robust way to learn Python. First, try to write code on paper and run in mind (Dry Run) then move to the system. Writing code on paper will help us get familiar quickly with the syntax and the concept store in the deep memory. While writing the code, try to use proper functions and suitable variables names.
    • There are many editors available for Python programming which highlights the syntax related issue automatically. So we don’t need to pay lot of attention of these mistakes.
    • 4. Keep Practicing
    • The next important step is to do the practice. It needs to implementing the Python concepts through the code. We should be consistence to our daily coding practice.
    • Consistency is the key of success in any aspect of life not only in programming. Writing code daily will help to develop muscle memory.
    • We can do the problem exercise of related concepts or solve at least 2 or 3 problems of Python. It may seem hard but muscle memory plays large part in programing. It will take us ahead from those who believe only the reading concept of Python is sufficient.
    • 5. Make Notes as Needed
    • Creating notes by own is an excellent method to learn the concepts and syntax of Python. It will establish stability and focus that helps you become a Python developer. Make brief and concise notes with relevant information and include appropriate examples of the subject concerned.
    • Maintain own notes are also helped to learn fast. A study published in Psychological Science that –
    • The students who were taking longhand notes in the studies were forced to be more selective — because you can’t write as fast as you can type.
    • 6. Discuss Concepts with Other
    • Coding seems to be solitary activity, but we can enhance our skills by interacting with the others. We should discuss our doubts to the expert or friends who are learning Python. This habit will help to get additional information, tips and tricks, and solution of coding problems. One of the best advantages of Python, it has a great community. Therefore, we can also learn from passionate Python enthusiasts.
    • 7. Do small Projects
    • After understanding Python’s basic concept, a beginner should try to work on small projects. It will help to understand Python more deeply and become more component in it. Theoretical knowledge is not enough to get command over the Python language. These projects can be anything as long as they teach you something. You can start with the small projects such as calculator app, a tic-toc-toe game, an alarm clock app, a to-do list, student or customer management system, etc.
    • Once you get handy with a small project, you can easily shift toward your interesting domain (Machine Learning, Web Development, etc.).
    • 8. Teach Others
    • There is a famous saying that “If you want to learn something then you should teach other”. It is also true in case of learning Python. Share your information to other students via creating blog posts, recording videos or taking classes in local training center. It will help us to enhance the understanding of Python and explore the unseen loopholes in your knowledge. If you don’t want to do all these, join the online forum and post your answers on Python related questions.
    • 9. Explore Libraries and Frameworks
    • Python consists of vast libraries and various frameworks. After getting familiar with Python’s basic concepts, the next step is to explore the Python libraries. Libraries are essential to work with the domain specific projects. In the following section, we describe the brief introduction of the main libraries.
    • TensorFlow – It is an artificial intelligence library which allows us to create large scale AI based projects.
    • Django – It is an open source framework that allows us to develop web applications. It is easy, flexible, and simple to manage.
    • Flask – It is also an open source web framework. It is used to develop lightweight web applications.
    • Pandas – It is a Python library which is used to perform scientific computations.
    • Keras – It is an open source library, which is used to work around the neural network.
    • There are many libraries in Python. Above, we have mentioned a few of them.
    • 10. Contribute to Open Source
    • As we know, Python is an open source language that means it is freely available for everyone. We can also contribute to Python online community to enhance our knowledge. Contributing to open source projects is the best way to explore own knowledge. We also receive the feedback, comments or suggestions for work that we submitted. The feedback will enable the best practices for Python programming and help us to become a good Python developer.
    • Usage of Python
    • Python is a general purpose, open source, high-level programming language and also provides number of libraries and frameworks. Python has gained popularity because of its simplicity, easy syntax and user-friendly environment. The usage of Python as follows.
    • Desktop Applications
    • Web Applications
    • Data Science
    • Artificial Intelligence
    • Machine Learning
    • Scientific Computing
    • Robotics
    • Internet of Things (IoT)
    • Gaming
    • Mobile Apps
    • Data Analysis and Preprocessing
    • In the next topic, we will discuss the Python Application, where we have defined Python’s usage in detail.
  • Python Features

    Python provides many useful features which make it popular and valuable from the other programming languages. It supports object-oriented programming, procedural programming approaches and provides dynamic memory allocation. We have listed below a few essential features.

    1) Easy to Learn and Use

    Python is easy to learn as compared to other programming languages. Its syntax is straightforward and much the same as the English language. There is no use of the semicolon or curly-bracket, the indentation defines the code block. It is the recommended programming language for beginners.

    2) Expressive Language

    Python can perform complex tasks using a few lines of code. A simple example, the hello world program you simply type print(“Hello World”). It will take only one line to execute, while Java or C takes multiple lines.

    3) Interpreted Language

    Python is an interpreted language; it means the Python program is executed one line at a time. The advantage of being interpreted language, it makes debugging easy and portable.

    4) Cross-platform Language

    Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to develop the software for several competing platforms by writing a program only once.

    5) Free and Open Source

    Python is freely available for everyone. It is freely available on its official website www.python.org. It has a large community across the world that is dedicatedly working towards make new python modules and functions. Anyone can contribute to the Python community. The open-source means, “Anyone can download its source code without paying any penny.”

    6) Object-Oriented Language

    Python supports object-oriented language and concepts of classes and objects come into existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to programmer to write reusable code and develop applications in less code.

    7) Extensible

    It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our Python code. It converts the program into byte code, and any platform can use that byte code.

    8) Large Standard Library

    It provides a vast range of libraries for the various fields such as machine learning, web developer, and also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development.

    9) GUI Programming Support

    Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.

    10) Integrated

    It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like C,C++ Java. It makes easy to debug the code.

    11. Embeddable

    The code of the other programming language can use in the Python source code. We can use Python source code in another programming language as well. It can embed other language into our code.

    12. Dynamic Memory Allocation

    In Python, we don’t need to specify the data-type of the variable. When we assign some value to the variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned integer value 15 to x, then we don’t need to write int x = 15. Just write x = 15.

  • Python Tutorial | Python Programming Language

    Python tutorial provides basic and advanced concepts of Python. Our Python tutorial is designed for beginners and professionals.

    Python is a simple, general purpose, high level, and object-oriented programming language.

    Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of Python programming.

    Our Python tutorial includes all topics of Python Programming such as installation, control statements, Strings, Lists, Tuples, Dictionary, Modules, Exceptions, Date and Time, File I/O, Programs, etc. There are also given Python interview questions to help you better understand Python Programming.

    What is Python

    Python is a general-purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures.

    Python is an easy-to-learn yet powerful and versatile scripting language, which makes it attractive for Application Development.

    With its interpreted nature, Python’s syntax and dynamic typing make it an ideal language for scripting and rapid application development.

    Python supports multiple programming patterns, including object-oriented, imperative, and functional or procedural programming styles.

    Python is not intended to work in a particular area, such as web programming. It is a multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.

    We don’t need to use data types to declare variable because it is dynamically typed, so we can write a=10 to assign an integer value in an integer variable.

    Python makes development and debugging fast because no compilation step is included in Python development, and the edit-test-debug cycle is very fast.

    Python has many web-based assets, open-source projects, and a vibrant community. Learning the language, working together on projects, and contributing to the Python ecosystem are all made very easy for developers.

    Because of its straightforward language framework, Python is easier to understand and write code in. This makes it a fantastic programming language for novices. Additionally, it assists seasoned programmers in writing clearer, error-free code.

    Python is an open-source, cost-free programming language. It is utilized in several sectors and disciplines as a result.

    In Python, code readability and maintainability are important. As a result, even if the code was developed by someone else, it is easy to understand and adapt by some other developer.

    Python has many third-party libraries that can be used to make its functionality easier. These libraries cover many domains, for example, web development, scientific computing, data analysis, and more.

    Python Basic Syntax

    There is no use of curly braces or semicolon in Python programming language. It is English-like language. But Python uses the indentation to define a block of code. Indentation is nothing but adding whitespace before the statement when it is needed. For example –

    def func():  
    
           statement 1  
    
           statement 2  
    
           …………………  
    
           …………………  
    
             statement N

    In the above example, the statements that are the same level to the right belong to the function. Generally, we can use four whitespaces to define indentation.

    Instead of Semicolon as used in other languages, Python ends its statements with a NewLine character.

    Python is a case-sensitive language, which means that uppercase and lowercase letters are treated differently. For example, ‘name’ and ‘Name’ are two different variables in Python.

    In Python, comments can be added using the ‘#’ symbol. Any text written after the ‘#’ symbol is considered a comment and is ignored by the interpreter. This trick is useful for adding notes to the code or temporarily disabling a code block. It also helps in understanding the code better by some other developers.

    ‘If’, ‘otherwise’, ‘for’, ‘while’, ‘try’, ‘except’, and ‘finally’ are a few reserved keywords in Python that cannot be used as variable names. These terms are used in the language for particular reasons and have fixed meanings. If you use these keywords, your code may include errors, or the interpreter may reject them as potential new Variables.

    Why learn Python?

    Python provides many useful features to the programmer. These features make it the most popular and widely used language. We have listed below few-essential features of Python.

    • Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
    • Expressive Language: It allows programmers to express complex concepts in just a few lines of code or reduces Developer’s Time.
    • Interpreted Language: Python does not require compilation, allowing rapid development and testing. It uses Interpreter instead of Compiler.
    • Object-Oriented Language: It supports object-oriented programming, making writing reusable and modular code easy.
    • Open Source Language: Python is open source and free to use, distribute and modify.
    • Extensible: Python can be extended with modules written in C, C++, or other languages.
    • Learn Standard Library: Python’s standard library contains many modules and functions that can be used for various tasks, such as string manipulation, web programming, and more.
    • GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and PyQt, allowing developers to create desktop applications easily.
    • Integrated: Python can easily integrate with other languages and technologies, such as C/C++, Java, and . NET.
    • Embeddable: Python code can be embedded into other applications as a scripting language.
    • Dynamic Memory Allocation: Python automatically manages memory allocation, making it easier for developers to write complex programs without worrying about memory management.
    • Wide Range of Libraries and Frameworks: Python has a vast collection of libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a wide range of problems.
    • Versatility: Python is a universal language in various domains such as web development, machine learning, data analysis, scientific computing, and more.
    • Large Community: Python has a vast and active community of developers contributing to its development and offering support. This makes it easy for beginners to get help and learn from experienced developers.
    • Career Opportunities: Python is a highly popular language in the job market. Learning Python can open up several career opportunities in data science, artificial intelligence, web development, and more.
    • High Demand: With the growing demand for automation and digital transformation, the need for Python developers is rising. Many industries seek skilled Python developers to help build their digital infrastructure.
    • Increased Productivity: Python has a simple syntax and powerful libraries that can help developers write code faster and more efficiently. This can increase productivity and save time for developers and organizations.
    • Big Data and Machine Learning: Python has become the go-to language for big data and machine learning. Python has become popular among data scientists and machine learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.

    Where is Python used?

    Python is a general-purpose, popular programming language, and it is used in almost every technical field. The various areas of Python use are given below.

    • Data Science: Data Science is a vast field, and Python is an important language for this field because of its simplicity, ease of use, and availability of powerful data analysis and visualization libraries like NumPy, Pandas, and Matplotlib.
    • Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI – Graphical User Interface-based Desktop Applications. There are better languages for this field, but it can be used with other languages for making Applications.
    • Console-based Applications: Python is also commonly used to create command-line or console-based applications because of its ease of use and support for advanced features such as input/output redirection and piping.
    • Mobile Applications: While Python is not commonly used for creating mobile applications, it can still be combined with frameworks like Kivy or BeeWare to create cross-platform mobile applications.
    • Software Development: Python is considered one of the best software-making languages. Python is easily compatible with both from Small Scale to Large Scale software.
    • Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language for artificial intelligence and machine learning because of the availability of powerful libraries such as TensorFlow, Keras, and PyTorch.
    • Web Applications: Python is commonly used in web development on the backend with frameworks like Django and Flask and on the front end with tools like JavaScript and HTML.
    • Enterprise Applications: Python can be used to develop large-scale enterprise applications with features such as distributed computing, networking, and parallel processing.
    • 3D CAD Applications: Python can be used for 3D computer-aided design (CAD) applications through libraries such as Blender.
    • Machine Learning: Python is widely used for machine learning due to its simplicity, ease of use, and availability of powerful machine learning libraries.
    • Computer Vision or Image Processing Applications: Python can be used for computer vision and image processing applications through powerful libraries such as OpenCV and Scikit-image.
    • Speech Recognition: Python can be used for speech recognition applications through libraries such as SpeechRecognition and PyAudio.
    • Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced numerical computing capabilities for tasks like data analysis, machine learning, and more.
    • Education: Python’s easy-to-learn syntax and availability of many resources make it an ideal language for teaching programming to beginners.
    • Testing: Python is used for writing automated tests, providing frameworks like unit tests and pytest that help write test cases and generate reports.
    • Gaming: Python has libraries like Pygame, which provide a platform for developing games using Python.
    • IoT: Python is used in IoT for developing scripts and applications for devices like Raspberry Pi, Arduino, and others.
    • Networking: Python is used in networking for developing scripts and applications for network automation, monitoring, and management.
    • DevOps: Python is widely used in DevOps for automation and scripting of infrastructure management, configuration management, and deployment processes.
    • Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial modeling and analysis.
    • Audio and Music: Python has libraries like Pyaudio, which is used for audio processing, synthesis, and analysis, and Music21, which is used for music analysis and generation.
    • Writing scripts: Python is used for writing utility scripts to automate tasks like file operations, web scraping, and data processing.

    Python Popular Frameworks and Libraries

    Python has wide range of libraries and frameworks widely used in various fields such as machine learning, artificial intelligence, web applications, etc. We define some popular frameworks and libraries of Python as follows.

    • Web development (Server-side) – Django Flask, Pyramid, CherryPy
    • GUIs based applications – Tk, PyGTK, PyQt, PyJs, etc.
    • Machine Learning – TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
    • Mathematics – Numpy, Pandas, etc.
    • BeautifulSoup: a library for web scraping and parsing HTML and XML
    • Requests: a library for making HTTP requests
    • SQLAlchemy: a library for working with SQL databases
    • Kivy: a framework for building multi-touch applications
    • Pygame: a library for game development
    • Pytest: a testing framework for Python
    • Django REST framework: a toolkit for building RESTful APIs
    • FastAPI: a modern, fast web framework for building APIs
    • Streamlit: a library for building interactive web apps for machine learning and data science
    • NLTK: a library for natural language processing

    Python Conditional Statements

    Conditional statements help us to execute a particular block for a particular condition. In this tutorial, we will learn how to use conditional expression to execute a different block of statements. Python provides if and else keywords to set up logical conditions. The elif keyword is also used as a conditional statement.

    Example code for if..else statement

    x = 10  
    
    y = 5  
    
      
    
    if x > y:  
    
        print("x is greater than y")  
    
    else:  
    
        print("y is greater than or equal to x")

    In the above code, we have two variables, x, and y, with 10 and 5, respectively. Then we used an if..else statement to check if x is greater than y or vice versa. If the first condition is true, the statement “x is greater than y” is printed. If the first condition is false, the statement “y is greater than or equal to x” is printed instead.

    The if keyword checks the condition is true and executes the code block inside it. The code inside the else block is executed if the condition is false. This way, the if..else statement helps us to execute different blocks of code based on a condition.

    We will learn about this in more detail in the further article for the Python tutorial.

    Python Loops

    Sometimes we may need to alter the flow of the program. The execution of a specific code may need to be repeated several times. For this purpose, the programming languages provide various loops capable of repeating some specific code several times. Consider the following tutorial to understand the statements in detail.

    Python For Loop

    fruits = ["apple", "banana", "cherry"]  
    
    for x in fruits:  
    
    print(x)

    Python While Loop

    i = 1   
    
    while i < 6:   
    
    print(i)   
    
    i += 1

    In the above example code, we have demonstrated using two types of loops in Python – For loop and While loop.

    The For loop is used to iterate over a sequence of items, such as a list, tuple, or string. In the example, we defined a list of fruits and used a for loop to print each fruit, but it can also be used to print a range of numbers.

    The While loop repeats a code block if the specified condition is true. In the example, we have initialized a variable i to 1 and used a while loop to print the value of i until it becomes greater than or equal to 6. The i += 1 statement is used to increment the value of i in each iteration.

    We will learn about them in the tutorial in detail.

    Python Functional Programming

    This section of the Python tutorial defines some important tools related to functional programming, such as lambda and recursive functions. These functions are very efficient in accomplishing complex tasks. We define a few important functions, such as reduce, map, and filter. Python provides the functools module that includes various functional programming tools. Visit the following tutorial to learn more about functional programming.

    Recent versions of Python have introduced features that make functional programming more concise and expressive. For example, the “walrus operator”:= allows for inline variable assignment in expressions, which can be useful when working with nested function calls or list comprehensions.

    Python Function

    1. Lambda Function – A lambda function is a small, anonymous function that can take any number of arguments but can only have one expression. Lambda functions are often used in functional programming to create functions “on the fly” without defining a named function.
    2. Recursive Function – A recursive function is a function that calls itself to solve a problem. Recursive functions are often used in functional programming to perform complex computations or to traverse complex data structures.
    3. Map Function – The map() function applies a given function to each item of an iterable and returns a new iterable with the results. The input iterable can be a list, tuple, or other.
    4. Filter Function – The filter() function returns an iterator from an iterable for which the function passed as the first argument returns True. It filters out the items from an iterable that do not meet the given condition.
    5. Reduce Function – The reduce() function applies a function of two arguments cumulatively to the items of an iterable from left to right to reduce it to a single value.
    6. functools Module – The functools module in Python provides higher-order functions that operate on other functions, such as partial() and reduce().
    7. Currying Function – A currying function is a function that takes multiple arguments and returns a sequence of functions that each take a single argument.
    8. Memoization Function – Memoization is a technique used in functional programming to cache the results of expensive function calls and return the cached Result when the same inputs occur again.
    9. Threading Function – Threading is a technique used in functional programming to run multiple tasks simultaneously to make the code more efficient and faster.

    Python Modules

    Python modules are the program files that contain Python code or functions. Python has two types of modules – User-defined modules and built-in modules. A module the user defines, or our Python code saved with .py extension, is treated as a user-define module.

    Built-in modules are predefined modules of Python. To use the functionality of the modules, we need to import them into our current working program.

    Python modules are essential to the language’s ecosystem since they offer reusable code and functionality that can be imported into any Python program. Here are a few examples of several Python modules, along with a brief description of each:

    Math: Gives users access to mathematical constants and pi and trigonometric functions.

    Datetime: Provides classes for a simpler way of manipulating dates, times, and periods.

    Os – Enables interaction with the base operating system, including administration of processes and file system activities.

    Random – The random function offers tools for generating random integers and picking random items from a list.

    JSON – JSON is a data structure that can be encoded and decoded and is frequently used in online APIs and data exchange. This module allows dealing with JSON.

    Re – Supports regular expressions, a potent text-search and text-manipulation tool.

    Collections – Provides alternative data structures such as sorted dictionaries, default dictionaries, and named tuples.

    Numpy is a core toolkit for scientific computing that supports numerical operations on arrays and matrices.

    Pandas: It provides high-level data structures and operations for dealing with time series and other structured data types.

    Requests: Offers a simple user interface for web APIs and performs HTTP requests.

    Python File I/O

    Files are used to store data in a computer disk. In this tutorial, we explain the built-in file object of Python. We can open a file using Python script and perform various operations such as writing, reading, and appending. There are various ways of opening a file. We are explained with the relevant example. We will also learn to perform read/write operations on binary files.

    Python’s file input/output (I/O) system offers programs to communicate with files stored on a disc. Python’s built-in methods for the file object let us carry out actions like reading, writing, and adding data to files.

    The open() method in Python makes a file object when working with files. The name of the file to be opened and the mode in which the file is to be opened are the two parameters required by this function. The mode can be used according to work that needs to be done with the file, such as “r” for reading, “w” for writing, or “a” for attaching.

    After successfully creating an object, different methods can be used according to our work. If we want to write in the file, we can use the write() functions, and if you want to read and write both, then we can use the append() function and, in cases where we only want to read the content of the file we can use read() function.

    Binary files containing data in a binary rather than a text format may also be worked with using Python. Binary files are written in a manner that humans cannot directly understand. The rb and wb modes can read and write binary data in binary files.

    Python Exceptions

    An exception can be defined as an unusual condition in a program resulting in an interruption in the flow of the program.

    Whenever an exception occurs, the program stops the execution, and thus the other code is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error.

    Python exceptions are an important aspect of error handling in Python programming. When a program encounters an unexpected situation or error, it may raise an exception, which can interrupt the normal flow of the program.

    In Python, exceptions are represented as objects containing information about the error, including its type and message. The most common type of Exception in Python is the Exception class, a base class for all other built-in exceptions.

    To handle exceptions in Python, we use the try and except statements. The try statement is used to enclose the code that may raise an exception, while the except statement is used to define a block of code that should be executed when an exception occurs.

    For example, consider the following code:

    try:  
    
        x = int ( input ("Enter a number: "))  
    
        y = 10 / x  
    
        print ("Result:", y)  
    
    except ZeroDivisionError:  
    
        print ("Error: Division by zero")  
    
    except ValueError:  
    
        print ("Error: Invalid input")

    In this code, we use the try statement to attempt to perform a division operation. If either of these operations raises an exception, the matching except block is executed.

    Python also provides many built-in exceptions that can be raised in similar situations. Some common built-in exceptions include IndexErrorTypeError, and NameError. Also, we can define our custom exceptions by creating a new class that inherits from the Exception class.

    Python CSV

    A CSV stands for “comma separated values”, which is defined as a simple file format that uses specific structuring to arrange tabular data. It stores tabular data such as spreadsheets or databases in plain text and has a common format for data interchange. A CSV file opens into the Excel sheet, and the rows and columns data define the standard format.

    We can use the CSV.reader function to read a CSV file. This function returns a reader object that we can use to repeat over the rows in the CSV file. Each row is returned as a list of values, where each value corresponds to a column in the CSV file.

    For example, consider the following code:

    import csv  
    
      
    
    with open('data.csv', 'r') as file:  
    
        reader = csv.reader(file)  
    
        for row in reader:  
    
            print(row)

    Here, we open the file data.csv in read mode and create a csv.reader object using the csv.reader() function. We then iterate over the rows in the CSV file using a for loop and print each row to the console.

    We can use the CSV.writer() function to write data to a CSV file. It returns a writer object we can use to write rows to the CSV file. We can write rows by calling the writer () method on the writer object.

    For example, consider the following code:

    import csv  
    
      
    
    data = [    ['Name', 'Age', 'Country'],  
    
        ['Alice', '25', 'USA'],  
    
        ['Bob', '30', 'Canada'],  
    
        ['Charlie', '35', 'Australia']  
    
    ]  
    
      
    
    with open('data.csv', 'w') as file:  
    
        writer = csv.writer(file)  
    
        for row in data:  
    
            writer.writerow(row)

    In this program, we create a list of lists called data, where each inner list represents a row of data. We then open the file data.csv in write mode and create a CSV.writer object using the CSV.writer function. We then iterate over the rows in data using a for loop and write each row to the CSV file using the writer method.

    Python Sending Mail

    We can send or read a mail using the Python script. Python’s standard library modules are useful for handling various protocols such as PoP3 and IMAP. Python provides the smtplib module for sending emails using SMTP (Simple Mail Transfer Protocol). We will learn how to send mail with the popular email service SMTP from a Python script.

    Python Sending Emails

    Python Magic Methods

    The Python magic method is the special method that adds “magic” to a class. It starts and ends with double underscores, for example, _init_ or _str_.

    The built-in classes define many magic methods. The dir() function can be used to see the number of magic methods inherited by a class. It has two prefixes and suffix underscores in the method name.

    • Python magic methods are also known as dunder methods, short for “double underscore” methods because their names start and end with a double underscore.
    • Magic methods are automatically invoked by the Python interpreter in certain situations, such as when an object is created, compared to another object, or printed.
    • Magic methods can be used to customize the behavior of classes, such as defining how objects are compared, converted to strings, or accessed as containers.
    • Some commonly used magic methods include init for initializing an object, str for converting an object to a string, eq for comparing two objects for equality, and getitem and setitem for accessing items in a container object.

    For example, the str magic method can define how an object should be represented as a string. Here’s an example:

    class Person:  
    
        def __init__(self, name, age):  
    
            self.name = name  
    
            self.age = age  
    
          
    
        def __str__(self):  
    
            return f"{self.name} ({self.age})"

    In this example, the str method is defined to return a formatted string representation of the Person object with the person’s name and age.

    Another commonly used magic method is eq, which defines how objects should be compared for equality. Here’s an example:

    
    
    1. def __init__(self, x, y):  
    2.     self.x = x  
    3.     self.y = y  
    4.   
    5. def __eq__(self, other):  
    6.     return self.x == other.x and self.y == other.y  

    In this example, the eq method is defined to return True if two Point objects have the same x and y coordinates and False otherwise.

    Python Oops Concepts

    Everything in Python is treated as an object, including integer values, floats, functions, classes, and none. Apart from that, Python supports all oriented concepts. Below is a brief introduction to the Oops concepts of Python.

    • Classes and Objects – Python classes are the blueprints of the Object. An object is a collection of data and methods that act on the data.
    • Inheritance – An inheritance is a technique where one class inherits the properties of other classes.
    • Constructor – Python provides a special method __init__() which is known as a constructor. This method is automatically called when an object is instantiated.
    • Data Member – A variable that holds data associated with a class and its objects.
    • Polymorphism – Polymorphism is a concept where an object can take many forms. In Python, polymorphism can be achieved through method overloading and method overriding.
    • Method Overloading – In Python, method overloading is achieved through default arguments, where a method can be defined with multiple parameters. The default values are used if some parameters are not passed while calling the method.
    • Method Overriding – Method overriding is a concept where a subclass implements a method already defined in its superclass.
    • Encapsulation – Encapsulation is wrapping data and methods into a single unit. In Python, encapsulation is achieved through access modifiers, such as public, private, and protected. However, Python does not strictly enforce access modifiers, and the naming convention indicates the access level.
    • Data Abstraction: A technique to hide the complexity of data and show only essential features to the user. It provides an interface to interact with the data. Data abstraction reduces complexity and makes code more modular, allowing developers to focus on the program’s essential features.

    To read the Oops concept in detail, visit the following resources.

    • Python Oops Concepts
    • Python Objects and classes
    • Python Constructor
    • Python Inheritance
    • Python Polymorphism

    Python Advance Topics

    Python includes many advances and useful concepts that help the programmer solve complex tasks. These concepts are given below.

    Python Iterator

    An iterator is simply an object that can be iterated upon. It returns one Object at a time. It can be implemented using the two special methods, __iter__() and __next__().

    Iterators in Python are objects that allow iteration over a collection of data. They process each collection element individually without loading the entire collection into memory.

    For example, let’s create an iterator that returns the squares of numbers up to a given limit:

    class Squares:

    def __init__(self, limit):  
    
            self.limit = limit  
    
            self.n = 0  
    
      
    
        def __iter__(self):  
    
            return self  
    
      
    
        def __next__(self):  
    
            if self.n <= self.limit:  
    
                square = self.n ** 2  
    
                self.n += 1  
    
                return square  
    
            else:  
    
                raise StopIteration  
    
      
    
    numbers = Squares(5)  
    
    for n in numbers:  
    
        print(n)

    Output:0 1 4 9 16 25

    In this example, we have created a class Squares that acts as an iterator by implementing the __iter__() and __next__() methods. The __iter__() method returns the Object itself, and the __next__() method returns the next square of the number until the limit is reached.

    To learn more about the iterators, visit our Python Iterators tutorial.

    Python Generators

    Python generators produce a sequence of values using a yield statement rather than a return since they are functions that return iterators. Generators terminate the function’s execution while keeping the local state. It picks up right where it left off when it is restarted. Because we don’t have to implement the iterator protocol thanks to this feature, writing iterators is made simpler. Here is an illustration of a straightforward generator function that produces squares of numbers:

    def square_numbers(n):  
    
        for i in range(n):  
    
            yield i**2  
    
      
    
    # create a generator object  
    
    generator = square_numbers(5)  
    
      
    
    # print the values generated by the generator  
    
    for num in generator:  
    
        print(num)

    Output:0 1 4 9 16

    Python Modifiers

    Python Decorators are functions used to modify the behavior of another function. They allow adding functionality to an existing function without modifying its code directly. Decorators are defined using the @ symbol followed by the name of the decorator function. They can be used for logging, timing, caching, etc. Here’s an example of a decorator function that adds timing functionality to another function:

    import time  
    
    def time_it(func):  
    
        def wrapper(*args, **kwargs):  
    
            start = time.time()  
    
            result = func(*args, **kwargs)  
    
            end = time.time()  
    
            print(f"{func.__name__} took {end-start:.2f} seconds to run.")  
    
            return result  
    
        return wrapper  
    
      
    
    def my_function():  
    
        time.sleep(2)  
    
        print("Function executed.")  
    
      
    
    my_function()

    In the above example, the time_it decorator function takes another function as an argument and returns a wrapper function. The wrapper function calculates the time to execute the original function and prints it to the console. The @time_it decorator is used to apply the time_it function to the my_function function. When my_function is called, the decorator is executed, and the timing functionality is added.

    Python MySQL

    Python MySQL is a powerful relational database management system. We must set up the environment and establish a connection to use MySQL with Python. We can create a new database and tables using SQL commands in Python.

    • Environment Setup: Installing and configuring MySQL Connector/Python to use Python with MySQL.
    • Database Connection: Establishing a connection between Python and MySQL database using MySQL Connector/Python.
    • Creating New Database: Creating a new database in MySQL using Python.
    • Creating Tables: Creating tables in the MySQL database with Python using SQL commands.
    • Insert Operation: Insert data into MySQL tables using Python and SQL commands.
    • Read Operation: Reading data from MySQL tables using Python and SQL commands.
    • Update Operation: Updating data in MySQL tables using Python and SQL commands.
    • Join Operation: Joining two or more tables in MySQL using Python and SQL commands.
    • Performing Transactions: Performing a group of SQL queries as a single unit of work in MySQL using Python.

    Other relative points include handling errors, creating indexes, and using stored procedures and functions in MySQL with Python.

    Python MongoDB

    MongoDB is a popular NoSQL database that stores data in JSON-like documents. It is schemaless and provides high scalability and flexibility for data storage. We can use MongoDB with Python using the PyMongo library, which provides a simple and intuitive interface for interacting with MongoDB.

    Here are some common tasks when working with MongoDB in Python:

    1. Environment Setup:Install and configure MongoDB and PyMongo library on your system.
    2. Database Connection:Connect to a MongoDB server using the MongoClient class from PyMongo.
    3. Creating a new database:Use the MongoClient Object to create a new database.
    4. Creating collections:Create collections within a database to store documents.
    5. Inserting documents: Insert new documents into a collection using the insert_one() or insert_many() methods.
    6. Querying documents: Retrieve documents from a collection using various query methods like find_one(), find(), etc.
    7. Updating documents: Modify existing documents in a collection using update_one() or update_many() methods.
    8. Deleting documents: Remove documents from a collection using the delete_one() or delete_many() methods.
    9. Aggregation: Perform aggregation operations like grouping, counting, etc., using the aggregation pipeline framework.
    10. Indexing: Improve query performance by creating indexes on fields in collections.

    There are many more advanced topics in MongoDB, such as data sharding, replication, and more, but these tasks cover the basics of working with MongoDB in Python.

    Python SQLite

    Relational databases are built and maintained using Python SQLite, a compact, serverless, self-contained database engine. Its mobility and simplicity make it a popular option for local or small-scale applications. Python has a built-in module for connecting to SQLite databases called SQLite3, enabling developers to work with SQLite databases without difficulties.

    Various API methods are available through the SQLite3 library that may be used to run SQL queries, insert, update, and remove data, as well as get data from tables. Additionally, it allows transactions, allowing programmers to undo changes in case of a problem. Python SQLite is a fantastic option for creating programs that need an embedded database system, including desktop, mobile, and modest-sized web programs. SQLite has become popular among developers for lightweight apps with database functionality thanks to its ease of use, portability, and smooth connection with Python.

    Python CGI

    Python CGI is a technology for running scripts through web servers to produce dynamic online content. It offers a communication channel and a dynamic content generation interface for external CGI scripts and the web server. Python CGI scripts may create HTML web pages, handle form input, and communicate with databases. Python CGI enables the server to carry out Python scripts and provide the results to the client, offering a quick and effective approach to creating dynamic online applications.

    Python CGI scripts may be used for many things, including creating dynamic web pages, processing forms, and interacting with databases. Since Python, a potent and popular programming language, can be utilized to create scripts, it enables a more customized and flexible approach to web creation. Scalable, safe, and maintainable online applications may be created with Python CGI. Python CGI is a handy tool for web developers building dynamic and interactive online applications.

    Asynchronous Programming in Python

    Asynchronous programming is a paradigm for computer programming that enables independent and concurrent operation of activities. It is frequently used in applications like web servers, database software, and network programming, where several tasks or requests must be handled concurrently.

    Python has asyncio, Twisted, and Tornado among its libraries and frameworks for asynchronous programming. Asyncio, one of these, offers a simple interface for asynchronous programming and is the official asynchronous programming library in Python.

    Coroutines are functions that may be halted and restarted at specific locations in the code and are utilized by asyncio. This enables numerous coroutines to operate simultaneously without interfering with one another. For constructing and maintaining coroutines, the library offers several classes and methods, including asyncio.gather(), asyncio.wait(), and asyncio.create_task().

    Event loops, which are in charge of planning and operating coroutines, are another feature of asyncio. By cycling between coroutines in a non-blocking way, the event loop controls the execution of coroutines and ensures that no coroutine blocks another. Additionally, it supports timers and scheduling callbacks, which may be helpful when activities must be completed at specified times or intervals.

    Python Concurrency

    The term “concurrency” describes a program’s capacity to carry out several tasks at once, enhancing the program’s efficiency. Python offers several modules and concurrency-related methods, including asynchronous programming, multiprocessing, and multithreading. While multiprocessing involves running many processes simultaneously on a system, multithreading involves running numerous threads concurrently inside a single process.

    The threading module in Python enables programmers to build multithreading. It offers classes and operations for establishing and controlling threads. Conversely, the multiprocessing module allows developers to design and control processes. Python’s asyncio module provides asynchronous programming support, allowing developers to write non-blocking code that can handle multiple tasks concurrently. Using these techniques, developers can write high-performance, scalable programs that can handle multiple tasks concurrently.

    Python’s threading module enables the concurrent execution of several threads within a single process, which is helpful for I/O-bound activities.

    For CPU-intensive operations like image processing or data analysis, multiprocessing modules make it possible to execute numerous processes concurrently across multiple CPU cores.

    The asyncio module supports asynchronous I/O and permits the creation of single-threaded concurrent code using coroutines for high-concurrency network applications.

    With libraries like Dask, PySpark, and MPI, Python may also be used for parallel computing. These libraries allow workloads to be distributed across numerous nodes or clusters for better performance.

    Web Scrapping using Python

    The process of web scraping is used to retrieve data from websites automatically. Various tools and libraries extract data from HTML and other online formats. Python is among the most widely used programming languages for web scraping because of its ease of use, adaptability, and variety of libraries.

    We must take a few steps to accomplish web scraping using Python. We must first decide which website to scrape and what information to gather. Then, we can submit a request to the website and receive the HTML content using Python’s requests package. Once we have the HTML text, we can extract the needed data using a variety of parsing packages, like Beautiful Soup and lxml.

    We can employ several strategies, like slowing requests, employing user agents, and using proxies, to prevent overburdening the website’s server. It is also crucial to abide by the terms of service for the website and respect its robots.txt file.

    Data mining, lead creation, pricing tracking, and many more uses are possible for web scraping. However, as unauthorized web scraping may be against the law and unethical, it is essential to utilize it professionally and ethically.

    Natural Language Processing (NLP) using Python

    A branch of artificial intelligence (AI) called “natural language processing” (NLP) studies how computers and human language interact. Thanks to NLP, computers can now understand, interpret, and produce human language. Due to its simplicity, versatility, and strong libraries like NLTK (Natural Language Toolkit) and spaCy, Python is a well-known programming language for NLP.

    For NLP tasks, including tokenization, stemming, lemmatization, part-of-speech tagging, named entity identification, sentiment analysis, and others, NLTK provides a complete library. It has a variety of corpora (big, organized text collections) for developing and evaluating NLP models. Another well-liked library for NLP tasks is spaCy, which offers quick and effective processing of enormous amounts of text. It enables simple modification and expansion and comes with pre-trained models for various NLP workloads.

    NLP may be used in Python for various practical purposes, including chatbots, sentiment analysis, text categorization, machine translation, and more. NLP is used, for instance, by chatbots to comprehend and reply to user inquiries in a natural language style. Sentiment analysis, which may be helpful for brand monitoring, customer feedback analysis, and other purposes, employs NLP to categorize text sentiment (positive, negative, or neutral). Text documents are categorized using natural language processing (NLP) into pre-established categories for spam detection, news categorization, and other purposes.

    Python is a strong and useful tool when analyzing and processing human language. Developers may carry out various NLP activities and create useful apps that can communicate with consumers in natural language with libraries like NLTK and spaCy.

    Conclusion:

    In this tutorial, we’ve looked at some of Python’s most important features and ideas, including variables, data types, loops, functions, modules, and more. More complex subjects, including web scraping, natural language processing, parallelism, and database connection, have also been discussed. You will have a strong basis to continue learning about Python and its applications using the information you have learned from this lesson.

    Remember that practicing and developing code is the best method to learn Python. You may find many resources at javaTpoint to support your further learning, including documentation, tutorials, online groups, and more. You can master Python and use it to create wonderful things if you work hard and persist.

    Prerequisite

    Before learning Python, you must have the basic knowledge of programming concepts.

    Audience

    Our Python tutorial is designed to help beginners and professionals.

    Problem

    We assure that you will not find any problem in this Python tutorial. But if there is any mistake, please post the problem in contact form.

  • JavaScript Objects

    What is an Object?

    JavaScript is an object-based language and in JavaScript almost everything is an object or acts like an object. So, to work with JavaScript effectively and efficiently we need to understand how objects work as well as how to create your own objects and use them.

    A JavaScript object is just a collection of named values. These named values are usually referred to as properties of the object. If you remember from the JavaScript arrays chapter, an array is a collection of values, where each value has an index (a numeric key) that starts from zero and increments by one for each value. An object is similar to an array, but the difference is that you define the keys yourself, such as name, age, gender, and so on. In the following sections we’ll learn about objects in detail.

    Creating Objects

    An object can be created with curly brackets {} with an optional list of properties. A property is a “key: value” pair, where the key (or property name) is always a string, and value (or property value) can be any data type, like strings, numbers, Booleans or complex data type like arrays, functions, and other objects. Additionally, properties with functions as their values are often called methods to distinguish them from other properties. A typical JavaScript object may look like this:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    };

    The above example creates an object called person that has three properties nameage, and gender and one method displayName(). The displayName() method displays the value of this.name, which resolves to person.name. This is the easiest and preferred way to create a new object in JavaScript, which is known as object literals syntax.

    The property names generally do not need to be quoted unless they are reserved words, or if they contain spaces or special characters (anything other than letters, numbers, and the _ and $ characters), or if they start with a number, as shown in the following example:

    Example

    let person = {
    
    "first name": "Peter",
    "current age": 28,
    gender: "Male"
    };

    Note: Since ECMAScript 5, reserved words can be used as object’s property names without quoting. However, you should avoid doing this for better compatibility.


    Accessing Object’s Properties

    To access or get the value of a property, you can use the dot (.), or square bracket ([]) notation, as demonstrated in the following example:

    Example

    let book = {
    
    "name": "Harry Potter and the Goblet of Fire",
    "author": "J. K. Rowling",
    "year": 2000
    }; // Dot notation document.write(book.author); // Prints: J. K. Rowling // Bracket notation document.write(book["year"]); // Prints: 2000

    The dot notation is easier to read and write, but it cannot always be used. If the name of the property is not valid (i.e. if it contains spaces or special characters), you cannot use the dot notation; you’ll have to use bracket notation, as shown in the following example:

    Example

    let book = {
    
    name: "Harry Potter and the Goblet of Fire",
    author: "J. K. Rowling",
    "publication date": "8 July 2000"
    }; // Bracket notation document.write(book["publication date"]); // Prints: 8 July 2000

    The square bracket notation offers much more flexibility than dot notation. It also allows you to specify property names as variables instead of just string literals, as shown in the example below:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; let key = prompt("Enter any property name to get its value"); alert(person[key]); // Outputs: Peter (if enter "name")

    Looping Through Object’s Properties

    You can iterate through the key-value pairs of an object using the for...in loop. This loop is specially optimized for iterating over object’s properties. Here’s an example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; // Iterating over object properties for(let i in person) {
    document.write(person&#91;i] + "&lt;br&gt;"); // Prints: name, age and gender
    }

    Setting Object’s Properties

    Similarly, you can set the new properties or update the existing one using the dot (.) or bracket ([]) notation, as demonstrated in the following example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; // Setting a new property person.country = "United States"; document.write(person.country); // Prints: United States person["email"] = "[email protected]"; document.write(person.email); // Prints: [email protected] // Updating existing property person.age = 30; document.write(person.age); // Prints: 30 person["name"] = "Peter Parker"; document.write(person.name); // Prints: Peter Parker

    Deleting Object’s Properties

    The delete operator can be used to completely remove properties from an object. Deleting is the only way to actually remove a property from an object. Setting the property to undefined or null only changes the value of the property. It does not remove property from the object.

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    }; // Deleting property delete person.age; alert(person.age); // Outputs: undefined

    Note: The delete operator only removes an object property or array element. It has no effect on variables or declared functions. However, you should avoid delete operator for deleting an array element, as it doesn’t change the array’s length, it just leaves a hole in the array.


    Calling Object’s Methods

    You can access an object’s method the same way as you would access properties—using the dot notation or using the square bracket notation. Here’s an example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male",
    displayName: function() {
        alert(this.name);
    }
    }; person.displayName(); // Outputs: Peter person["displayName"](); // Outputs: Peter

    Manipulating by Value vs. Reference

    JavaScript objects are reference types that mean when you make copies of them, you’re really just copying the references to that object. Whereas primitive values like strings and numbers are assigned or copied as a whole value. To better understand all this, let’s check out the following example:

    Example

    let message = "Hello World!";
    
    let greet = message; // Assign message variable to a new variable
    greet = "Hi, there!";
    
    document.write(message);  // Prints: Hello World!
    document.write(greet);  // Prints: Hi, there!

    In the above example, we have made a copy of a variable message and changed the value of that copy (i.e. variable greet). The two variables remain distinct and separate. But, if we do the same thing with an object, we will get a different result, as you see in the following example:

    Example

    let person = {
    
    name: "Peter",
    age: 28,
    gender: "Male"
    }; let user = person; // Assign person variable to a new variable user.name = "Harry"; document.write(person.name); // Prints: Harry document.write(user.name); // Prints: Harry

    You can clearly see, any changes made to the variable user also change the person variable; it happens because both variables reference the same object. So, simply copying the object does not actually clone it but copies the reference to that object.

  • JavaScript Functions

    What is Function?

    A function is a group of statements that perform specific tasks and can be kept and maintained separately form main program. Functions provide a way to create reusable code packages which are more portable and easier to debug. Here are some advantages of using functions:

    • Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again.
    • Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files.
    • Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.

    The following section will show you how to define and call functions in your scripts.

    Defining and Calling a Function

    The declaration of a function start with the function keyword, followed by the name of the function you want to create, followed by parentheses i.e. () and finally place your function’s code between curly brackets {}. Here’s the basic syntax for declaring a function:

    function functionName() {
    // Code to be executed
    }

    Here is a simple example of a function, that will show a hello message:

    Example

    // Defining function
    function sayHello() {
    
    alert("Hello, welcome to this website!");
    } // Calling function sayHello(); // 0utputs: Hello, welcome to this website!

    Once a function is defined it can be called (invoked) from anywhere in the document, by typing its name followed by a set of parentheses, like sayHello() in the example above.

    Note: A function name must start with a letter or underscore character not with a number, optionally followed by the more letters, numbers, or underscore characters. Function names are case sensitive, just like variable names.


    Adding Parameters to Functions

    You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they’re replaced at run time by the values (known as argument) provided to the function at the time of invocation.

    Parameters are set on the first line of the function inside the set of parentheses, like this:

    function functionName(parameter1parameter2parameter3) {
    // Code to be executed
    }

    The displaySum() function in the following example takes two numbers as arguments, simply add them together and then display the result in the browser.

    Example

    // Defining function
    function displaySum(num1, num2) {
    
    let total = num1 + num2;
    alert(total);
    } // Calling function displaySum(6, 20); // 0utputs: 26 displaySum(-5, 17); // 0utputs: 12

    You can define as many parameters as you like. However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called, otherwise its value becomes undefined. Let’s consider the following example:

    Example

    // Defining function
    function showFullname(firstName, lastName) {
    
    alert(firstName + " " + lastName);
    } // Calling function showFullname("Clark", "Kent"); // 0utputs: Clark Kent showFullname("John"); // 0utputs: John undefined

    Default Values for Function Parameters ES6

    With ES6, now you can specify default values to the function parameters. This means that if no arguments are provided to function when it is called these default parameters values will be used. This is one of the most awaited features in JavaScript. Here’s an example:

    Example

    function sayHello(name = 'Guest') {
    
    alert('Hello, ' + name);
    } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John

    While prior to ES6, to achieve the same we had to write something like this:

    Example

    function sayHello(name) {
    
    let name = name || 'Guest'; 
    alert('Hello, ' + name);
    } sayHello(); // 0utputs: Hello, Guest sayHello('John'); // 0utputs: Hello, John

    To learn about other ES6 features, please check out the JavaScript ES6 features chapter.


    Returning Values from a Function

    A function can return a value back to the script that called the function as a result using the return statement. The value may be of any type, including arrays and objects.

    The return statement usually placed as the last line of the function before the closing curly bracket and ends it with a semicolon, as shown in the following example.

    Example

    // Defining function
    function getSum(num1, num2) {
    
    let total = num1 + num2;
    return total;
    } // Displaying returned value alert(getSum(6, 20)); // 0utputs: 26 alert(getSum(-5, 17)); // 0utputs: 12

    A function can not return multiple values. However, you can obtain similar results by returning an array of values, as demonstrated in the following example.

    Example

    // Defining function
    function divideNumbers(dividend, divisor){
    
    let quotient = dividend / divisor;
    let arr = &#91;dividend, divisor, quotient];
    return arr;
    } // Store returned value in a variable let all = divideNumbers(10, 2); // Displaying individual values alert(all[0]); // 0utputs: 10 alert(all[1]); // 0utputs: 2 alert(all[2]); // 0utputs: 5

    Working with Function Expressions

    The syntax that we’ve used before to create functions is called function declaration. There is another syntax for creating a function that is called a function expression.

    Example

    // Function Declaration
    function getSum(num1, num2) {
    
    let total = num1 + num2;
    return total;
    } // Function Expression let getSum = function(num1, num2) {
    let total = num1 + num2;
    return total;
    };

    Once function expression has been stored in a variable, the variable can be used as a function:

    Example

    let getSum = function(num1, num2) {
    
    let total = num1 + num2;
    return total;
    }; alert(getSum(5, 10)); // 0utputs: 15 let sum = getSum(7, 25); alert(sum); // 0utputs: 32

    Note: There is no need to put a semicolon after the closing curly bracket in a function declaration. But function expressions, on the other hand, should always end with a semicolon.

    Tip: In JavaScript functions can be stored in variables, passed into other functions as arguments, passed out of functions as return values, and constructed at run-time.

    The syntax of the function declaration and function expression looks very similar, but they differ in the way they are evaluated, check out the following example:

    Example

    declaration(); // Outputs: Hi, I'm a function declaration!
    function declaration() {
    
    alert("Hi, I'm a function declaration!");
    } expression(); // Uncaught TypeError: undefined is not a function let expression = function() {
    alert("Hi, I'm a function expression!");
    };

    As you can see in the above example, the function expression threw an exception when it was invoked before it is defined, but the function declaration executed successfully.

    JavaScript parse declaration function before the program executes. Therefore, it doesn’t matter if the program invokes the function before it is defined because JavaScript has hoisted the function to the top of the current scope behind the scenes. The function expression is not evaluated until it is assigned to a variable; therefore, it is still undefined when invoked.

    ES6 has introduced even shorter syntax for writing function expression which is called arrow function, please check out the JavaScript ES6 features chapter to learn more about it.


    Understanding the Variable Scope

    However, you can declare the variables anywhere in JavaScript. But, the location of the declaration determines the extent of a variable’s availability within the JavaScript program i.e. where the variable can be used or accessed. This accessibility is known as variable scope.

    By default, variables declared within a function have local scope that means they cannot be viewed or manipulated from outside of that function, as shown in the example below:

    Example

    // Defining function
    function greetWorld() {
    
    let greet = "Hello World!";
    alert(greet);
    } greetWorld(); // Outputs: Hello World! alert(greet); // Uncaught ReferenceError: greet is not defined

    However, any variables declared in a program outside of a function has global scope i.e. it will be available to all script, whether that script is inside a function or outside. Here’s an example:

    Example

    let greet = "Hello World!";
     
    // Defining function
    function greetWorld() {
    
    alert(greet);
    } greetWorld(); // Outputs: Hello World! alert(greet); // Outputs: Hello World!
  • JavaScript Loops

    Different Types of Loops in JavaScript

    Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. JavaScript now supports five different types of loops:

    • while — loops through a block of code as long as the condition specified evaluates to true.
    • do…while — loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true.
    • for — loops through a block of code until the counter reaches a specified number.
    • for…in — loops through the properties of an object.
    • for…of — loops over iterable objects such as arrays, strings, etc.

    In the following sections, we will discuss each of these loop statements in detail.


    The while Loop

    This is the simplest looping statement provided by JavaScript.

    The while loop loops through a block of code as long as the specified condition evaluates to true. As soon as the condition fails, the loop is stopped. The generic syntax of the while loop is:

    while(condition) {
    // Code to be executed
    }

    The following example defines a loop that will continue to run as long as the variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

    Example

    let i = 1;
    while(i <= 5) {    
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    i++;
    }

    Note: Make sure that the condition specified in your loop eventually goes false. Otherwise, the loop will never stop iterating which is known as infinite loop. A common mistake is to forget to increment the counter variable (variable i in our case).


    The do…while Loop

    The do-while loop is a variant of the while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true. The generic syntax of the do-while loop is:

    do {
    // Code to be executed
    }
    while(condition);

    The JavaScript code in the following example defines a loop that starts with i=1. It will then print the output and increase the value of variable i by 1. After that the condition is evaluated, and the loop will continue to run as long as the variable i is less than, or equal to 5.

    Example

    let i = 1;
    do {
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    i++;
    } while(i <= 5);

    Difference Between while and do…while Loop

    The while loop differs from the do-while loop in one important way — with a while loop, the condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false, the loop will never be executed.

    With a do-while loop, on the other hand, the loop will always be executed once even if the conditional expression evaluates to false, because unlike the while loop, the condition is evaluated at the end of the loop iteration rather than the beginning.


    The for Loop

    The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times. Its syntax is:

    for(initializationconditionincrement) {
    // Code to be executed
    }

    The parameters of the for loop statement have following meanings:

    • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
    • condition — it is evaluated at the beginning of each iteration. If it evaluates to true, the loop statements execute. If it evaluates to false, the execution of the loop ends.
    • increment — it updates the loop counter with a new value each time the loop runs.

    The following example defines a loop that starts with i=1. The loop will continued until the value of variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs:

    Example

    for(let i=1; i<=5; i++) {
    
    document.write("&lt;p&gt;The number is " + i + "&lt;/p&gt;");
    }

    The for loop is particularly useful for iterating over an array. The following example will show you how to print each item or element of the JavaScript array.

    Exampl

    // An array with some elements
    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Loop through all the elements in the array 
    for(let i=0; i<fruits.length; i++) {
    
    document.write("&lt;p&gt;" + fruits&#91;i] + "&lt;/p&gt;");
    }

    The for…in Loop

    The for-in loop is a special type of a loop that iterates over the properties of an object, or the elements of an array. The generic syntax of the for-in loop is:

    for(variable in object) {
    // Code to be executed
    }

    The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name of current property or the index of the current array element.

    The following example will show you how to loop through all properties of a JavaScript object.

    Example

    // An object with some properties 
    let person = {"name": "Clark", "surname": "Kent", "age": "36"};
     
    // Loop through all the properties in the object  
    for(let prop in person) {  
    
    document.write("&lt;p&gt;" + prop + " = " + person&#91;prop] + "&lt;/p&gt;"); 
    }

    Similarly, you can loop through the elements of an array, like this:

    Example

    // An array with some elements
    let fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
     
    // Loop through all the elements in the array 
    for(let i in fruits) {  
    
    document.write("&lt;p&gt;" + fruits&#91;i] + "&lt;/p&gt;");
    }

    Note: The for-in loop should not be used to iterate over an array where the index order is important. You should better use a for loop with a numeric index.


    The for…of Loop ES6

    ES6 introduces a new for-of loop which allows us to iterate over arrays or other iterable objects (e.g. strings) very easily. Also, the code inside the loop is executed for each element of the iterable object.

    The following example will show you how to loop through arrays and strings using this loop.

    Example

    // Iterating over array
    let letters = ["a", "b", "c", "d", "e", "f"];
    
    for(let letter of letters) {
    
    console.log(letter); // a,b,c,d,e,f
    } // Iterating over string let greet = "Hello World!"; for(let character of greet) {
    console.log(character); // H,e,l,l,o, ,W,o,r,l,d,!
    }

    To learn about other ES6 features, please check out the JavaScript ES6 features chapter.