For enquiries call:

Phone

+1-469-442-0620

April flash sale-mobile

HomeBlogProgrammingWhat is Python, it's basics and getting started with Python

What is Python, it's basics and getting started with Python

Published
05th Sep, 2023
Views
view count loader
Read it in
22 Mins
In this article
    What is Python, it's basics and getting started with Python

    Learning something new is always interesting and exciting but how to learn makes it challenging. It is believed that learning how to learn is the most critical task while learning a new programming language. A proper strategy to learn makes the journey easier and smooth. Let us look into such essential learning strategies which will help you learn the basics of Python and guide you through the journey of becoming a programmer.

    Essential Python learning strategies

    • Code Regularly: It is important for a beginner to practice Python coding on a regular basis which will develop a muscle memory. At first it might seem to be difficult but a regular practice of half an hour will make your basics stronger.
    • Use Pen and Paper: Many learners have this question in mind, whether they should write codes using a pen and paper or not. It is recommended to write codes or take notes by hand as it is beneficial for long-term retention as you get a firm hold over writing flawless codes. Also, in a lot of interviews, you are asked to write codes on a white board.
    • Program as a Pair: With a friend or another learner completing a task together is called pair programming. It is a technique where two developers work at a single workstation. One of the developers should be the “driver” and the other should be the “navigator”. The “driver” writes the code, while the “navigator” helps guide the problem solving and reviews the code as it is written. Both the developers should switch between the roles.
    • Build new things: There are a lot of short exercises for beginners which will make you confident with Python. You should have good knowledge about basic data structures (strings, lists, dictionaries, sets), object-oriented programming, and writing classes. Here, let us discuss about what Python is all about, how to get started with Python and learn about the basics of Python.

    What is Python Programming?

    What is Python? Python is an interactive, object-oriented & multi purpose programming language which is easy to understand & use.

    Python is an interpreted, interactive, object-oriented and multi-purpose programming language created by Guido Van Rossum in the late 1980s. It is a programming language— a language which people and computers both can understand. It is powerful and has an easy-to-use syntax, making it perfect for beginners.

    Python is a flexible language which has the ability to write simple programs and also create large complex programming solutions. It is used extensively for web and internet developments, for mathematical and scientific computations of data and also in the field of game and graphics development. Some of the popular websites that use Python are Youtube, Instagram, Dropbox, Pinterest etc. Join the advanced python course online to learn more about Python and its capabilities.

    Why Choose Python?

    Why to Choose Python? Popularity, Interpretation, OpenSource, Portability and Simplicity.

    Whether you’re a beginner to programming or an experienced programmer designing a complex application, Python is a great choice because of its easily understandable nature and vast capabilities. 

    Some of the features of Python that make it irresistible to users:

    • Popularity: Python is considered as the 4th most popular and fastest growing programming language according to the Stack Overflow Developer Survey 2019. Python is used by the world’s most renowned Software Companies like Google, YouTube, Instagram, Netflix, Spotify, Quora and much more.
    • Interpretation: Python is an interpreted language which means the programs are passed straight to the interpreter which executes them directly; unlike compilers where the source code is converted to machine code before running.
    • OpenSource: Python is a free language developed under OSI-approved open-source license which makes it free to use and distribute even for commercial purposes.
    • Portability: Python code is portable, which means the code written in one platform will work in any other platform, having the Python interpreter installed.
    • Simplicity: Python’s coding style is very simple and clean which makes it easy to read and learn. It uses less keywords compared to other languages like C++ or Java. Developers tend to use it all the time because of its neat and organized code structure.

    How to Get Python?

    Python is an open-source software that comes pre-installed in Mac and works on most distributions of Linux and other platforms. However, you might need to download the latest version to get the most out of it.

    Choosing Python 

    Presently, there are two major versions of Python - 2.x and 3.x. However, at an early stage, you can use either of the two because there are very few differences between them. Also once you have learned one, the other one won’t be difficult to learn.

    In simple terms, if you’re starting to learn Python, the latest version 3.7.x would be more suitable since it comes with extra features with a number of bug fixes. On the other hand, you can use the version 2.7.x when you need support from third-party libraries to perform your task.

    Installing Python

    You can download the specific version of Python that suits your OS and processor (32-bit or 64-bit) from the Python Software Foundation (PSF).

    Installation pertaining to OS requirement:

    • Windows: In any Windows platform, you can directly download Python software from the PSF.
    • Linux: You can download the latest version of Python on Linux in the same manner. However, you can also use a package manner, if needed.
    • Mac: For Mac systems, download the software from PSF and then install it. Moreover, it is suggested to use a package manager like Homebrew for installing and managing different versions of Python.

    Python Shell

    After you have successfully installed Python in your system, you can check whether it is installed or not using the Python Interactive Shell:

    • Windows: Open the terminal and type python for Python 2.7 or py -3 for Python 3.
    • Linux: Open your terminal and simply run python.
    • Mac: Depending on the version of Python you’ve installed, open your terminal and run python or python3.

    The command prompt or the terminal will look somewhat like this:

    Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:21)
    [MSC v.1916 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>

    You can use the exit() to leave the Python shell or you can also use CTRL + D and then press the ENTER key to terminate the command prompt.

    What are the Basics of Python?

    Python is a very beautiful language and feels very natural to work with. It consists of a number of coding basics. Let us first start by running the universal Hello World program.

    The Hello World Program

    If you want to display a line in the terminal, you can do so by using the print statement:

    >>> print("HELLO WORLD!")

    The output will be displayed as follows:
    HELLO WORLD!

    Variables

    Variables are defined as containers or memory locations for storing data. The syntax of declaring a variable is variable_name = variable_value. However, it is recommended to use variables names like num1, my_int or mystring other than simple variables like x or y.

    Sensible names gives a clear indication of the type of variable and it is also useful for others to understand your code clearly. Thinking of others while writing your program will improve your coding skills.

    Built-in Data Types

    Python comprises of many built-in data types starting from numbers, strings, lists, tuples and dictionaries.

    Numbers

    Python supports many types of numbers like integers (1, 2, 55, 599, -99), floating points (1.0, 5.55,  661.1, -99.9),  Booleans (True or False) or complex numbers. We can perform addition and subtraction with numbers just like normal addition and subtraction we learnt in our school:

    >>> 1 + 5   # Addition
    6
    >>> num1 = 5
    >>> num2 = 5.01
    >>> num3 = num1 + num2
    >>> 10 - 5   # Subtraction
    5

    We can also compare numbers that will result in a boolean value:

    >>> 1 < 3
    True
    >>> 4 > 5
    False

    Python consists of a number of built-in functions that you can use to handle numbers:

    >>> float(13)
    13.0

    A float() function takes an integer and returns a floating point number.

    Other than functions, Python also has a number of data-type methods connected to each type of number. float.is_integer() is a data-type method which checks whether a floating point number is finite or not:

    >>> (10.1).is_integer()
    False
    >>> (5.0).is_integer()
    True 

    Strings

    A String is a list of characters in an organized manner. A character can be a number or letter or even a backslash. In simple words, they are lines enclosed in single or double quotes:

    >>> string1 = "hello"
    >>> string
    'hello'
    >>> string2 = 'hey'
    >>> string2
    "hey"

    In Python, we can combine strings in a series without any gaps. This is called Concatenation:

    >>> "Python is" + "easy"
    'Python is easy'

    We can also manipulate strings using functions:

    >>> len('Python')
    6

    Here, len() is a function that takes a string as an input and returns the size of the string.

    Data-type methods also exist for handling strings. string.capitalize() takes an input string and returns by capitalizing the first string:

    >>> lower_case_string = 'python'
    >>> lower_case_string.capitalize()
    'Python'
    >>> ('the Avengers').capitalize()
    'The Avengers' 

    Lists

    A list is an ordered sequence of elements in Python. Each element in a list is known as an item. They are similar to array in C or C++.
    Lists may consist of any data type like numbers or strings mixed together, or other lists or they may be empty too. The syntax is usual:

    >>> create_a_list = []
    >>> list_of_numbers = [1, 5, 10, 1000]
    >>> list_of_numbers
    [1, 5, 10, 1000]
    >>> list = ["ironman", "thor", "hulk"]
    >>> list
    ['ironman', 'thor', 'hulk']
    >>> mixed_list = ["Python", [1, 2, 3], True]
    >>> mixed_list
    ['Python', [1, 2, 3], True]

    Elements of lists can be accessed either from the start or the end. Also, you can create a new list just by accessing the elements:

    >>> list_of_numbers = [1, 5, 10, 1000]
    >>> new_list = list_of_numbers[0:2]
    >>> new_list
    [1, 5]

    Concatenation of lists using operators:

    >>> marvel = ["ironman", "thor", "hulk"]
    >>> dc = ["superman", "batman", "flash"]
    >>> multiverse = marvel + dc
    >>> multiverse
    [‘ironman’, ‘thor’, ‘hulk’, ‘superman’, ‘batman’, ‘flash’]

    The function of lists works in the same manner as of strings:

    >>> list_of_numbers = [1, 5, 10, 1000]
    >>> len(list_of_numbers)
    4

    len() returns the size of the list.

    Data-type methods like list.sort() and list.append() are used to sort  and append lists:

    #append
    >>> stationary = ["inkpen", "pencil", "eraser"]
    >>> stationary.append("sharpener")
    >>> fruits
    ['inkpen', 'pencil', 'eraser', 'sharpener']

    #sort
    >>> stationary.sort()
    >>> stationary
    [ 'eraser', 'inkpen', 'pencil', 'sharpener']

    Tuples

    Tuples are sequence of Python objects that cannot be changed after creation. They are similar to lists, the only difference being that lists are mutable.

    An example of a tuple:

    my_tuple = ("Alex", "Blanc", 27, "Technical Blogger")

    You can concatenate two tuples using operators just like lists:

    >>> tuple1 = (11, 29)
    >>> tuple2 = (30, 90)
    >>> tuple3 = tuple1 + tuple1
    >>> tuple3
    (11, 29, 30, 90)

    You can convert a tuple into a list by using the function list():

    >>> tuple1 = (100, 500)
    >>> list(tuple1)
    [100, 500]

    Since tuples cannot be changed after it is created, most of the data-type methods like sort() or append() or reverse() will not work on tuples.

    Dictionary

    A dictionary in Python is an unordered collection of associative arrays (or objects).
    An example of a dictionary of phone numbers:

    >>> phonebook = {}
    >>> phonebook["Alex"] = 9038478766
    >>> phonebook["Bob"] = 9098379264
    >>> phonebook["Charlie"] = 9017652781

    Conditions

    A conditional statement is a statement that handles the flow of execution depending on some condition.
    Statements can be compared or evaluated in Python using boolean expressions as follows:

    >>> x = 5
    >>> print(x == 5) # prints True
    >>> print(x == 2) # prints False

    You can also use the if-else statements to check if a statement is true or not:

    >>>if 2 > 3:
      print("2 is greater than 3")
      else:
      print("2 is not greater than 3")

    Loops

    You can use loops when you want to repeat a block of code in a fixed number of time. You can iterate in two different ways, the first is by using the while loop:

    >>> num = 1
    >>> while num <= 5:
        print(num)
        num = num + 1

    While the statement is true, the loop will iterate and the code will be executed. It will print the number from 1 to 5.

    Another way of implementing a loop is using the for statement:

    >>> for num in range(1, 10):
        print(num) 

    Here, the range starts from 1 and goes until 10. The loop iterates 10 times over the statement.

    Functions

    Functions in Python are a block of organized code which is useful in performing a single action. Syntax of defining a function is def function_name.

    An example of a function is:

    >>> def my_first_function():
    print("HELLO WORLD!")

    You can also return a value to the caller in a function using the return statement:

    >>> def multiply_by_2(a):
    return a * 2

    Classes and Objects

    An object in Python is a collection of variables and methods. A class is a blueprint for the object.

    For example, we can consider a prototype of a house as the class. It consists of all the details of the floors, walls, doors, windows etc. We can build the house on the basis of the details. So, house becomes the object. Objects are instances of a class.

    You can define a class in Python using the keyword class as follows: 

    >>> class My_First_Class:
        my_variable = "blah"

    You can create an object in Python which can be used to access different attributes of a class. This process of creating new object instances is called instantiation.

    An example to illustrate that:

    class My_First_Class:
    def func(self):
    print('Hello')
    ob = My_First_Class() #creating a class object

    Modules and Packages

    A module is a single file (or files) that are imported under one import and then used. In simple words, any Python file is a module. On the other hand, packages are simple directories consisting of multiple modules and packages themselves.

    Python consists of a number of packages and modules to increase the extent of the language. 

    Some of the useful built-in Python modules are:

    • math: This module gives access to mathematical functions from the standard library of C.
    • random: This module is a pseudo-random number generator.
    • datetime: This module comprises of classes by which you can manipulate dates and times.

    Pip is the standard package manager which is used to handle Python’s third party packages and modules in an efficient manner. It allows you to install the packages that are not part of the Python Standard Library. You can download Pip from pypi.org.

    Comments

    Comments can be in the form of module-level docstrings or inline explanations that are used to describe your code in a clear manner so that developers can understand. It starts with a hash (#) character and can extend to the end of the line.

    An example of a simple comment:
    # This is a comment

    An example of an inline comment:

    variable = "Hello World"  # This is an inline comment

    Errors and Exceptions 

    Python consists of two types of errors:

    • Syntax errors.
    • Exceptions or errors during execution.

    Syntax Errors

    Syntax errors occur when the Python parser is unable to understand a line of code. Most syntax errors occur because of incorrect indentation or arguments.

    An example to illustrate such:

    >>> if 2 < 5
       File "<stdin>", line 1
         if 2 < 5
                 ^
    SyntaxError: invalid syntax

    Here, the if statement is missing a colon(:)at the end of the statement which results into a syntax error.

    Exceptions

    Errors that occur during execution are known as exceptions. There are a number of built-in exceptions in Python.

    An example of an exception:

    >>> prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25}
    >>> prices['Eraser']
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        prices['Eraser']
    KeyError: 'Eraser'

    Here, dictionary prices is declared with the prices of three items. The KeyError is raised when the item Eraser is being accessed which is not present in prices. Learn more about exceptions in our blog- Python KeyError Exceptions and How to Handle Them.

    Semantic Errors

    A semantic error, also known as logic error, is an error that occurs because of an incorrect logic. They are much more difficult to catch as compared to syntax errors.

    These types of errors are complex in nature and generate incorrect or no output. The most common example of a semantic error is an infinite loop. Programmers in their early stage of learning encounter an infinite loop at least once.

    Top Cities Where KnowledgeHut Conduct Python Certification Course Online

    Python Course in BangalorePython Course in ChennaiPython Course in Singapore
    Python Course in DelhiPython Course in DubaiPython Course in Indore
    Python Course in PunePython Course in BerlinPython Course in Trivandrum
    Python Course in NashikPython Course in MumbaiPython Certification in Melbourne
    Python Course in HyderabadPython Course in KolkataPython Course in Noida

    What are the Different ways of Coding in Python?

    When you’re in the process of learning a new programming language, you might want things to be simple and your path of becoming a good programmer to be smooth and clear. The first approach to this will be choosing an efficient way of running and executing code in Python.

    There are mainly three primary approaches to coding in Python— the shell, IDLE and the code editor.

    The Shell

    Python provides the Python Shell, which is useful for simple, one-line statements. It waits for the input commands from the user and returns the result of the execution. It is the least powerful among the three.

    You can open shell in your system and run the following command:

    >>> 11 + 9
    20 

    Here, the Python Shell evaluated the statement 11 + 9 , performed the addition operation and displayed the result 20.

    Another example of coding in shell:

    >>> import this

    When you execute this statement, you can see the Zen of Python. It is a collection of 19 principles which acts as a guide to writing idiomatic Python code.

    However, the shell has a drawback. The code written in a Python Shell is not persistent which means the code cannot be reused. 

    IDLE

    IDLE stands for Integrated Development and Learning Environment. It is similar to the shell and contains both the Shell window and the Editor Window. You can create and save Python code because the IDLE allows code reusability. However, it still stands second in the rank powerfulness. 

    Code Editor

    A code editor is the most powerful among all the three. It is a text-editor program that is useful in editing source codes of computer programs. A code editor can be a single application or act as an Integrated Development Environment or IDE.

    There are a lot of code editors available in the market. Choosing a code-editor for your task might be a time-consuming work. 

    However, you can take into consideration some factors while choosing a code editor like easy to use, line numbering, auto-indentation, highlighting of syntax and availability of adding extra features.

    One of the most powerful and popular cross-platform code editor is the Sublime Text.  Other code editors might include gedit,  which is a bit simpler than Sublime. You can also use Notepad++, however it is only for Windows.

    Conclusion

    Though you have learned the basics of the Python Programming Language, here are some tricks and tricks for you to remember while coding in Python— 

    • Good coding is happy coding. Good code depends on the way you write a code. The key to a good code is to maintain a proper style. You can go through the blog on How To Write Beautiful Python Code With PEP 8 which focuses on enhancing the readability and consistency of code. 

    • The logic is the most crucial part when you’re writing a program. If you have a clear understanding of the concepts, you can easily shape your code into a logical program. And the most effective way to do that is to logically break your problem into different parts and then solve it one by one. 

    • The best way of learning how to code is by building a project-driven learning approach. There are a lot of free resources, online courses, books, and tutorials available. You can refer to the official Python documents - Python 2.7 or Python 3 for more information. 

    • And last but not the least, always keep brushing up the concepts. As a beginner, you might face difficulties in every step but always try and resolve your issues on your own. Test your skills and take up new challenges every day. 

    Let’s sum up what we have learnt so far in this article: 

    • What is Python programming and what is the need? 

    • How to install and run Python. 

    • What are the primitives of the Python programming language? 

    • What are the ways of Python coding? 

    When it comes to learning Python in a classroom setup, a google search for python programming classes near me a couple of years ago would have shown you our classroom programs in your city. What has changed is that now we now offer online learning programs for more than 3000 IT skills. Explore our IT course now. 

    Profile

    Priyankur Sarkar

    Data Science Enthusiast

    Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon