Python

Python Tutorial for Beginners (with video)

This is a Python tutorial for beginners.

1. Introduction

Python is one of the most widely used programming languages today. It first appeared in 1991. In this article, we will take a deep dive into Python.

You can also check this tutorial in the following video:

Python Tutorial For Beginners – video

 

2. What is Python?

Guido van Rossum created Python as a successor to the ABC programming language. The first version of Python got released in 1991. The most recent version is 3.9.1, which got released in December 2020.

Python is an interpreted language, which means that it has an interpreter instead of a compiler that converts code to machine language and executes it. This feature enables Python to be platform-independent. Python is also object-oriented, dynamically typed and garbage collected.

3. Why is Python so popular?

Python is an open-source, dynamic, high-level programming language. Python is slower in terms of execution than other programming languages like Java, C, etc. It is, however, more popular. The reason for this popularity is as follows:

  • Easy to code:
    It is a developer-friendly language, and it is effortless to learn the basic syntax of Python.
  • Free and Open Source:
    Python language is freely available. Since it is open-source, this means that source code is also visible to the public. So you can download and customize it.
  • Object-Oriented Language:
    One of the critical features of python is Object-Oriented programming. Python supports object-oriented language and concepts of classes, objects encapsulation, etc.
  • GUI Programming Support.
  • High-Level Language:
    Python is a high-level language, so developers don’t need to bother about system architecture and memory management.
  • Extensible feature:
    Python is an Extensible language. We can embed Python snippets in other languages as well.
  • Python is a Portable language:
    It is platform-independent.
  • Interpreted Language:
    Python is interpreted into bytecode, not compiled, which makes it easier to debug
  • Large Standard Library
    Python has a rich library of in-built functions. It is effortless to include other libraries in Python.
  • Dynamically Typed Language:
    Python is a dynamically-typed language. We do not need to specify the datatype of the variable.

4. Installation steps and verification

To get started with Python, we first have to install it on our systems. Generally, the Linux and Mac OS already have Python installed.

4.1 Verify Python version

To check if Python is present on your machine,

  • Open Command Prompt or cmd
  • Type the command:
 python -v

If Python is present, then the above command gives back the version number. If not, then the below message is displayed.

python tutorial - Checking Python version
Checking Python version

4.2 Install Python

 For Windows users, there are a couple of different ways to install Python

4.2.1 The Microsoft Store

  • Open the Microsoft Store.
  • In the window that opens, type “Python” in the search box.
  • Choose the latest version.
  • Hit “Get” button to start the installation.
python tutorial - Microsoft store Python installation
Microsoft store Python installation

Alternatively, we can also open cmd and type python and, hit Enter. The command will open the same window as above. The Python that gets installed is not the complete package. It is enough if you are a beginner at Python. However, for the advanced concepts of Python, the complete package is preferred.

4.2.2 Download the latest package from the official Python site.

The following are the steps to be followed:

  • Go to the official Python site.
  • Click on the Download Python button.
  • The file that gets downloaded is python-3.9.1-amd64.exe
  • Double click on the file and follow the steps.
python tutorial - Python.org installation
Python.org installation

The Python installed using the above steps is the complete Python package and is the recommended installation method. To verify that Python has installed correctly, repeat the steps for “Verify Python version.” You should be able to see output similar to this.

python tutorial - Python installed
Python installed

We can also install Python by using distributions like Anaconda. Anaconda is a package management and deployment system and greatly simplifies adding other libraries to Python. To download Anaconda, download visit this site. The Anaconda documentation is available here.

5. Python Tutorial – Getting started

There are multiple ways in which we can code using Python. We can use the inbuilt interpreter, code editors, and even software like Jupyter notebooks packaged in an Anaconda distribution.

5.1 Python interpreter

Python comes with a default interactive interpreter. To run the interpreter

  • Open a Command Prompt using the cmd command.
  • Type the command
python

Doing this opens an interpreter where we can start coding in Python right away. To exit the interpreter, press Ctrl key + Z and press Enter.

python tutorial - REPL or interpreter
REPL or interpreter

It is one of the easiest ways to start coding in Python. It becomes tedious for lengthy programs.

5.2 Code editors

There are multiple code editors available that provide support for Python. Some of the most popular code editors for Python are Visual Studio Code, Sublime text3, Atom, etc. Python also offers in-built code editors called IDLE that get installed with the Python installation. We will use the IDLE code editor for all our examples.

To open the IDLE code editor, In the Search box in Windows, type IDLE. The IDLE IDE is an excellent IDE for beginners.

python tutorial - IDLE IDE
IDLE IDE

6. Python Tutorial – The very first program

To get started with IDLE, we will write the first “Hello World” program.

  • Open IDLE IDE.
  • Click on the File menu and select New File
  • In the window that opens, write the code:
print (“Hello World”)
  • Click on File and Save the file in the location of your choice.
  • Then click on the Run menu and select the first option.

Alternatively, you can also press F5 key. This runs the program and outputs Hello World.

First Program in Python
First Program in Python

7. Python Syntax Tutorial

In this section, we will look at the various syntax rules related to Python

7.1 Python Indentation

Unlike other programming languages, the whitespace has significance for the Python interpreter. Python uses indentation to indicate a block of code.

For example, consider the program for checking if a code is odd or even.

script1.py

inputNumber = int(input("Enter a number: "))
if inputNumber % 2 ==0:
   print(str(inputNumber) + " is even") 
else:
   print(str(inputNumber) + " is odd")
Correct indentation
Correct indentation

The code above runs perfectly. If, however, in the code above, we forget to put an indent for the print line, the program will fail compilation.

script1.py

inputNumber = int(input("Enter a number: "))
if inputNumber % 2 ==0:
print(str(inputNumber) + " is even") 
else:
print(str(inputNumber) + " is odd")
Incorrect indentation
Incorrect indentation

7.2 Multi-Line statements

Generally, in Python, we write one statement on one line. However, Python allows multi-line statements. To write multi-line statements, we add a ‘\’ at the end of each line.

 For example:

multiLineStrings.py

multiLineString = "first line" + \
                  "second line" + \
                  "third line"

print (multiLineString)

This script will run and print out the three lines on a single line with spaces in between.

Multi Line Strings
Multi Line Strings

However, if we miss the ‘\’ at the end of the line, the script will fail with a compilation error.

Incorrect syntax error.
Incorrect syntax error.

7.3 Quotation marks

Python allows single ‘ ‘ or double quotes “ “ or even triple quotes ”’ ”’. The only constraint is that the quotation marks for each line need to be consistent. Meaning if a line starts with a single quote, then it should end with a single quote. For strings that span multiple lines, we use triple quotation marks. For such strings, we cannot use double or single quotation marks. At least not without the ‘\’ character.

The example program is as follows:

Quotation_strings.py

#Correct strings
str1 = ‘It is nice weather today!’
str2 = “Have a nice day.” 
str3 = """ All the world’s a stage, and all the men and women merely players.
           They have their exits and their entrances;
           And one man in his time plays many parts."""
str4 = """This is just one line but that is allowed."""

print (str1)
print (str2)
print (str3)
print (str4)
Quotations output
Quotations output

7.4 Comments and blank lines

We put comments in Python using the # sign. The Python interpreter completely ignores anything after the # sign. If there is a line with just whitespaces, then that is ignored by the Python interpreter also. The # sign comments a single line. There is no syntax for a block comment. However, if we use a multi-line string, i.e. (string in triple quotes) and we do not assign it to a variable, then Python considers it a comment.

commentExample.py

# print ("this is a comment").
""" print("this is a comment to
    although it spans multiple
    line.")"""
#print ("the line below this will also be ignored since its just whitespaces.")

str1 = """However this is not a comment
          since we have assigned it to a variable"""

print(str1)

All the earlier lines except the str1 are comments.

Comments
Comments

7.5 Case-sensitive

Python is a case sensitive language. Hence, the variable str1, Str1, STR1 are all different variables as per the Python interpreter. They are not interchangeable.

8. Python Keywords Tutorial

Just like most programming languages, Python also has some keywords that the Python interpreter reserves. As of now, there are 33 keywords in Python. We cannot use keywords as variables, function names, or any other identifier. I have grouped the keywords as per their use:

8.1 Value Keywords

These keywords are in uppercase and must be used as such. These keywords are boolean values.

  • False
  • True
  • None

8.2 Operator Keywords

We use these keywords for joining multiple conditions. The keywords are:

  • and
  • or
  • not
  • in
  • is

8.3 Control Flow Keywords

We can control the flow of the programs. We can use conditional logic.

  • if
  • else
  • elif

We can nest multiple if-else statements using the elif statements.

8.4 Loop or Iteration Keywords

Using these keywords, we can do repetitive tasks. The keywords are

  • for
  • while
  • break
  • continue
  • else

We can use the else keyword with the loop keywords as well as the if keyword in  Python.

8.5 Structure Keywords

We use these keywords to define functions, classes and context managers.

  • def
  • class
  • with
  • as
  • pass
  • lambda

8.6 Control return keywords

The following keywords, we can use to change the control of the program.

  • return
  • yield

8.7 Import Keywords

Python reserves these keywords for adding and handling external libraries in the program

  • import
  • from
  • as

8.8 Error handling Keywords

The keywords handle exceptions and errors in the Python program.

  • try
  • except
  • raise
  • finally
  • else
  • assert

8.9 Asynchronous programming Keywords

These keywords are for asynchronous programming. Asynchronous programming is an advanced topic and we will not explore it in this topic.

  • async
  • await

8.10 Variable-handling keywords

We can use these keywords for specific variables. The keywords are:

  • del
  • global
  • nonlocal

Python deprecated the keywords print and exec and replaced them with in-built functions.

9. Python Variables Tutorial

Python has dynamic typing, i.e., we do not need to define the datatype when we declare a variable. We can change the variable’s datatype to some other datatypes later as well. For example:

x =12 
…… 
 x =”It is nice today!”

The example code is valid in Python.

There are specific rules we use for variable names. They are as follows:

  • A variable name must start with a letter or the underscore character.
  • It cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • Variable names are case-sensitive (age, Age, and AGE are three different variables).
  • Python allows the Camel Case, for example, myVar, Pascal Case, i.e., MyVar, or the Snake Case, for instance, my_var for writing variable names with multiple words.

10. Python datatypes Tutorial

Like every programming language, Python has datatypes to assist in programming. The datatypes that Python supports are as follows:

Type of valuesdatatype name
Textstr
Numericint, float, complex
Collection of objects/text/numberslist, tuple, range
Mapdict
Setsset, frozenset
Booleanbool
Binarybytes, bytearray, memoryview
Different datatypes in Python

As mentioned before, Python is dynamically-typed. Hence, if we want to know the data type of a variable, we can use the type() function.

11. Simple Program

Python has a rich library of in-built functions, especially for the str datatype. Going through each of the methods is not possible. However, we will see a sample program where we use many keywords and datatypes together. To get a complete list of in-built functions, check the Python documentation library. We will look at a simple, sample program that uses a few of the most commonly-used built-in functions in Python.

Utilities.py

#To print anything on the console
print("Hello World!!\n")
print("***********************************************************\n")

#add to numbers we use the + operator.
#Subtract, multiply and divide are similar
print("Enter the first number: ")
num1 = int(input())

print("Enter the second number: ")
num2 = int(input())
sum1 = num1 + num2

#We cannot concat strings and numbers together.
#We need to cast to string by using str()
#Using + with 2 strings, concats or joins them together.
print("Sum is: " + str(sum1))
print("***********************************************************\n")

#int is automatically cast to a float during division
num3 = 12
num4 = 7

result = num3/num4
#We can also get a rounded result
roundedValue = round(num1/num2)
print(type(num3))
print(type(num4))
print(type(result))

print(str(result))
print(str(roundedValue))
print("***********************************************************\n")

num4 = 100
num5 = 200

#This will give a negative number
diff = num4 - num5

print(diff)
#But if we want the absolute value we can use the abs() function 
print(str(abs(diff)) + "\n")
print("***********************************************************\n")

#We can sort a list using an inbuilt function
lst = [27,16,250,3,10,54]
#Python will sort the list and print it out for us.
print(sorted(lst))
print("***********************************************************\n")

#String methods
#To remove whitespaces from a string, we use strip()
str1 = "                    This has a lot of whitespaces               "
print(str1.strip() + "\n")

#To reverse a string without loops.
str2="I would like to reverse this string."

#While this is not a in-built function , it is a very important construct for splicing strings. 
print(str2[:: -1] + "\n")
print("***********************************************************\n")

str3 = """ All the world’s a stage, and all the men and women merely players,
           They have their exits and their entrances,
           And one man in his time plays many parts."""

#To split a string, we use the split() method.
#If we do not specify a delimiter, the string is slit using whitespaces.
print(str3.split())
print('\n')

#To specify a delimiter, like ',' we do
'''When the string is split using a delimeter and not word by word, python will consider 
the new line and whitespaces as a part of the string.'''

print(str3.split(","))
print("***********************************************************\n")
Output of the Program
Output of the Program

12. Python Tutorial – Summary

In this python tutorial, we looked at the basics of the Python programming language and began coding with Python through examples.

Python is dynamically-typed, easy to use, and has a rich library of in-built functions. The functions we have seen in this article are just the tip of the iceberg that is Python.

You can learn more through our Python tutorials.

To get resources related to Python, please visit the python wiki page.

13. Related articles

14. Download the Source code

This was a tutorial on Python for beginners.

Download
You can download the full source code of this example here: Python Tutorial for Beginners

Last updated on Jan. 14th, 2022

Reshma Sathe

I am a recent Master of Computer Science degree graduate from the University Of Illinois at Urbana-Champaign.I have previously worked as a Software Engineer with projects ranging from production support to programming and software engineering.I am currently working on self-driven projects in Java, Python and Angular and also exploring other frontend and backend technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button