E-Books

Introduction to Python

What is Python

Python is a popular programming language. It was created by Guido van Rossum and released is 1991. It is used for Web development (server side), Software development, Mathematics, System scripting etc.

Why Python

Python works on different platforms / windows, Mac, Linux, Raspberry, pi etc.

Python has a simple syntax similar to the English language.

Python has syntax that allows developers to write programs with fewer lines that some other programming languages.

Python runs on an interpreter system meaning that code can be executed as soon as it is written.

History of Python

The idea of python started in early 1980.

Real implementation started in 1989.

Finally published in 1991 27 Feb.

Guido van Rossum Developed python while working in national research institute Netherlands.

Name Python : I chose python as a working title for the project, being in a slightly irreverent mood (and a big fan of monthly pythons flying circus.)

Python Versions

Python Version       Released Date

Python 1.0       -       January 1994

Python 1.5       -       December 31, 1997

Python 1.6       -       September 5, 2000

Python 2.0       -       October 16, 2000

Python 2.1       -       April 17, 2001

Python 2.2       -       December 21, 2001

Python 2.3       -       July 29, 2003

Python 2.4       -       November 30, 2004

Python 2.5       -       September 19, 2006

Python 2.6       -       October 1, 2008

Python 2.7       -       July 3, 2010

Python 3.0       -       December 3, 2008

Python 3.1       -       June 27, 2009

Python 3.2       -       February 20, 2011

Python 3.3       -       September 29, 2012

Python 3.4       -       March 16, 2014

Python 3.5       -       September 13, 2015

Python 3.6       -       December 23, 2016

Python 3.7       -       June 27, 2018

Python 3.8       -       October 14, 2019

Differences between Python 2.x and Python 3.x

There are two major versions of python, python 2 and python 3.

No backword compatibility.

It would be dangerous to port Python 3.x code in Python 2.x

Python 2 and python 3 are quite different.

Python 2.x is legacy.

Python 3.x is the present and future of the language.

Python 2 Python 3
Division operator work like C Division operator work like Mathematics
print “hello” print( “hello”)
Implicit str type is ASCII, explicit support for UNI Code. Implicit str type is UNICODE
range( ) and xrange( ) function Only range( ) function
Exception Handling as keyword is required
raw_input( ) for reading strings raw_input() is no more exists
input( ) function reads data with filtering input( ) function work like raw_input( )

How to download and install Python

To use python you need to install python on your computer.

There are multiple python to distribution available today.

1. Anaconda - Anaconda is a distribution of the Python and R programming languages for scientific computing, that aims to simplify package management and deployment. For download visit www.anaconda.com/download

2. PyCharm - PyCharm is an integrated development environment used for programming in Python. It provides code analysis, a graphical debugger, an integrated unit tester, integration with version control systems, and supports web development with Django. For download visit www.jetbrains.com/pycharm/download/

3. IDLE - IDLE is an integrated development environment for Python, which has been bundled with the default implementation of the Python language. For download visit https://www.python.org

Note : - That python 3.6.8 can be used on windows 7

32 bit Operating System - Download Windows x86 executable installer

64 bit Operating System - Download Windows x86-64 executable installer

How to get start Python ?

After installation is successfully completed you can start python in following ways.

1. Python Shell - Interactive mode ( Command line ).

2. Python IDLE - Script mode (Integrated Development Learning Environment).

Interactive mode (Command line)

Start -> Python Folder -> Python 3.6.8

python-interactive-mode

How to write multiline code in interactive mode?

You can write multi-line code in interactive mode using function

multi-line code in interactive mode

Exit form Interactive mode

Press CTRL + Z Or type quite()

Script mode - IDLE (Integrated Development Learning Environment)

A user can switch to script mode by creating a file from File -> New File.

1. Write Your Code

                    
# My First Python Program
print("Hello World!")
print("I am Learning Python Programming")
                    
                    

2. Save the Python Code

Save the file on your computer. Select File > Save as in the IDLE File Menu.

Python files have the file extension .py

3. Running a Program

Now go to Run menu and select Run module option or press F5 to run your script

Work effectively with IDLE

IDLE has lots of features, but you need to know about only a few of them.

1. TAB Completion

Start typing in some code, and then press the TAB key. IDLE will offer suggestions to help you complete your statement.

Recall code statements

Press Alt-P to recall the previous code statement.

Press Alt-N to recall to the next code statement.

3. Edit recalled code

You can edit it and move around the statement using the arrow key.

IDLE Menu

Recent file : See list of recent open files.

Save copy as - ALT + Shift + S: Save a copy of file with different name and location.

Exit IDLE - CTRL + Q : Exit form the IDLE

Restart Shell - Ctrl + F6: Restart the shell to clean the environment and reset display and exception handling.

Interrupt Execution - CTRL + Q : It means that the user gives the command to stop the execution of the program

Configure - IDLE : Configuration fonts, indentation, keybindings, text color themes, startup windows and size etc.

Python Style Rule and Conventions

There are list of some python style rule and convention that help you to write Python code

1. Semicolons ( ; )

The Python statement written in the form of sentence must not be terminated with semicolons.

2. Line length

The line length should be of maximum 79 characters if you use Python.

3. Indentations :

In Python indentation is use to create a block of statement and it is treated as unit the code blocks are indented by default with 4 spaces.

4. whitespace

Standard typographic rules are use for spaces.

5. Comments

The right style for module, function, method and in-line comments should always be used.

6. Statements

Generally only one statement per line should be written

7. Case Sensitive

Python language is case sensitive it treats upper and lower case characters differently.

Using Comments

In Python, comments are used to explain the purpose of the code, provide documentation, or temporarily disable certain parts of the code. Comments are ignored by the Python interpreter during execution. There are two ways to add comments in Python

1. Single-line comments:

Single-line comments begin with the # character and continue until the end of the line.

                    
# This is a single-line comment
print("Hello, World!")  # This is also a single-line comment

                    
                  

2. Multi-line comments:

Python doesn't have a built-in syntax for multi-line comments like some other programming languages. However, you can use triple quotes (''' or """) to create multi-line strings, which are often used as multi-line comments.

                  
'''
This is a multi-line comment.
It spans across multiple lines.
'''

"""
This is another way of creating a multi-line comment.
"""
print("Hello, World!")

                  
                

Python Character set

Character set is a set of valid characters that a language can recognize. There are two type of character sets in Python 1. Source Characters and Escape Sequence.

1. Source Characters

a. Alphabetic Characters: This includes uppercase and lowercase letters from the English alphabet (a to z and A to Z).

b. Digits: Numeric digits from 0 to 9.

c. Special Characters : +, -, *, /, =, ==, !=, <,>, <=,>=,[], (), {}, ^, #, %, &, | , ~ , etc.

2. Escape sequences

An Escape character is a backslash \ followed by the character you want to insert. Some character work only interactive mode.

\'           Single Quote

\\           Backslash

\n           New Line

\r           Carriage Return

\t           Tab

\b           Backspace

\a           Alert

\ooo       Octal value

\xhh       Hex value

Token

The smallest individual unit or element in a program is known as a token a lexical unit. Each token should be separated from the other by a space or tab. Python has the following tokens which are discussed below: keywords, identifiers, literals (constants), punctuators and operators.

Keywords or Reserved words

At the time of designing a language, some words are reserved to do specific task. Such words are called as keywords or reserved words. In Python, they are case sensitive.

Note: All Keywords in Python are in small case except True, False and None.

                    
import keyword

for kw in keyword.kwlist:
    print(kw, end=', ')

"""
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
"""
                    
                  

Identifier

Identifier is user-defined name given to different parts of program, such as variables, classes, objects, functions and modules names.

Rules for Python Identifier:

1. A Identifier name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

2. A Identifier name must start with a letter or the underscore character

3. A Identifier name cannot start with a number

4. Identifier names are case-sensitive (age, Age and AGE are three different variables)

5. A Identifier name cannot be any of the Python keywords.

Literals

Literals can be defined as a data which is given in a variable or constant. For example 7, -29, “Hello” are literals. Literals are fixed numeric or non-numeric value. Python supports the following literals.

String Literals

A string is a sequence any of characters enclosed within either single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).

                  
str1 = 'Python String in Single Quote'
str2 = "Python String in Double Quote"
str3 = '''Python String in Triple Quote'''
str4 = """Python String in Triple Quote"""

print(str1, str2, str3, str4)
                  
                

Multiline Strings in Python

You can assign a multiline string to a variable by using three quotes

                  
str1 = ''' This is
Multi-line
String in Python '''

str2 = """ This is
another Multi-line
String in Python """

print(str1, str2)
                  
                

Numeric Literals

Python supports three type of numeric literals integer, float and complex.

                  
a = 7 # Integer literal
b = 2.53 # Float literal
c = 2.53j # Complex literal

print(a, b, c)
                  
                

Boolean Literals

Boolean literals are used to denote Boolean values. They contain either True or False.

                  
isActive = True  # Boolean literal
isApproved = False  # Boolean literal

print(isActive, isApproved)
                  
                

Variables in Python

A variable is the name of a memory location where data (literals or constants) is stored. You must initialize a variable at the declaration time in Python. Every variable are object to a class in python.

Rules for Naming Variables

1. It can only contain letters (A-Z or a-z), digits (0-9), and underscores _ .

2. A variable name must start with a letter (A-Z or a-z) or an underscore (_).

3. It cannot start with a number (e.g., 1num is invalid).

4. Variable names are case-sensitive (num and Num are different).

5. Python keywords (like if, else, while, for, etc.) cannot be used as variable names.

Variable Inislization in Python

Initialization is the process that sets the initial value of a variable.

The equal sign = used to assign values to variables.

Identity of Variable: The identity of a variable refers to its memory address. The id() method is used to retrieve this memory address.

                  
name = "Raj Kumar"
age = 24

print(name, age)

print("Memory Address of name:", id(name))
    

Methods to manipulate variable in Python

In Python, the left side of the assignment operator = must always be a variable

                  
  5 = x  # SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?"
  x + 2 = 10 # SyntaxError: cannot assign to expression
                  
                

Assigning same value to multiple variable in Python

In Python, you can assign the same value to multiple variables in a single line using this syntax:

                  
a = b = c = "Python"
print(a)   # Output: Python
print(b)   # Output: Python
print(c)   # Output: Python
                  
                

Assigning multiple values to multiple variables in Python

Python allows you to assign multiple values to multiple variables in a single line. This is called multiple assignment.

                  
  # var1, var2, var3 = value1, value2, value3

  x, y, z = 10, 20, 30
  print(x)   # Output: 10
  print(y)   # Output: 20
  print(z)   # Output: 30
                  
                

Assigning None to a Variable in Python

In Python, None is a special built-in constant that represents the absence of a value or a null value.

                  
  status = None

  # Later in the code, you can assign an actual value
  status = "Completed"
  print(status)  # Output: Completed                    
                  
                

L-value and R-value in Python

L-value (Left Value):

1. Refers to a memory location (a variable) that can appear on the left-hand side of an assignment.

2. It must be a valid variable name.

3. It can store data.

                  
  x = 10
  # x is the L-value — it's a variable that stores the value 10
                  
                

R-value (Right Value):

1. Refers to the data or value that is assigned to the variable.

2. It appears on the right-hand side of the assignment.

3. It can be a constant, expression, function call, etc.

                  
  x = 5 + 2
  # 5 + 2 is the R-value — the result (7) is assigned to x
                  
                

Mutable vs Immutable in Python

In Python, every object is either mutable (changeable) or immutable (unchangeable).

Mutable Objects

Mutable objects can be changed after they are created. This means you can modify their content without changing their identity (memory address).

Examples : list, dict (dictionary), set, bytearray

                  
  my_list = [1, 2, 3]
  my_list.append(4)
  print(my_list)  # Output: [1, 2, 3, 4]
                  
                

Immutable Objects

Immutable objects cannot be changed after they are created. Any change creates a new object in memory.

Examples: int, float, str (string), tuple, bool, frozenset, bytes

                  
  name = "Deepak"
  name = name + " Raj"
  print(name)  # Output: Deepak Raj
                  
                

Memory Address Test:

You can use the id() function to check the identity of objects.

                  
  x = [1, 2]
  print(id(x))
  x.append(3)
  print(id(x))  # Same ID → Mutable
  
  y = "hello"
  print(id(y))
  y += " world"
  print(id(y))  # Different ID → Immutable
                  
                

Type Casting in Python

Type casting means converting one data type to another. Python provides built-in functions for type conversion

1. Implicit Type Casting (Automatic)

Python automatically converts one data type to another when needed.

                  
  # int is automatically converted to float.

  x = 10      # int
  y = 2.5     # float
  z = x + y
  print(z)          # Output: 12.5
  print(type(z))    # Output: <class 'float'>
                  
                

2. Explicit Type Casting (Manual)

You manually convert a data type using functions like:

Function Description
int(x) Converts x to an integer.
float(x) Converts x to a float.
str(x) Converts x to a string.
bool(x) Converts x to a boolean.
list(x) Converts x to a list.
tuple(x) Converts x to a tuple.
set(x) Converts x to a set (unique items).

Convert String to Integer

                  
  num = int("100")
  print(num + 50)   # Output: 150
                  
                

Convert Float to Integer

                  
  x = int(3.9)
  print(x)          # Output: 3
                  
                

Convert Integer to String

                  
  x = 25
  text = str(x)
  print("My age is " + text)
                  
                

Convert List to Tuple

                  
  lst = [1, 2, 3]
  tup = tuple(lst)
  print(tup)        # Output: (1, 2, 3)
                  
                

⚠️ Caution: Invalid conversions will raise errors

                  
  x = int("abc")   # ❌ Error: invalid literal for int()
                  
                

Data Types in Python

In Python, data types specify the type of value a variable holds. Python is a dynamically typed language, so you don’t need to declare the data type — Python figures it out automatically.

data-type-in-python

Checking Data Type

                  
  x = 10
  print(type(x))  # Output: <class 'int'>
                  
                

input() Function in Python

The input() function is used to take input from the user through the keyboard.

variable = input("Prompt message")

input() displays the prompt (optional) and waits for the user to type something and press Enter.

It always returns the input as a string (even if you type a number).

      
name = input("Enter your name: ")
print("Hello,", name)

age = int(input("Enter your age: "))
print("You will be", age + 1, "next year.")
      
    

print() Function in Python

The print() function is used to display output on the screen.

Basic Syntax

                  
  print(object, ..., sep=' ', end='\n')

  object → The value(s) to print.

  sep → Separator (default is space ' ').

  end → What to print at the end (default is newline \n).
                  
                

Basic Example

                  
  print("Hello, Python!") 

  🖥️ Output
  Hello, Python!
                  
                

Printing Multiple Values

                  
  x = 10
  y = 20
  print("x =", x, "and y =", y)

  🖥️ Output
  x = 10 and y = 20                    
                  
                

Using sep Parameter

                  
  print("2025", "04", "15", sep="-")

  🖥️ Output
  2025-04-15
                  
                

Using end Parameter

                  
  print("Hello", end=" ")
  print("World!")
  
  🖥️ Output
  Hello World!
                  
                

Formatted Print using f-strings

              
  name = "Deepak"
  age = 25
  print(f"My name is {name} and I am {age} years old.")

  🖥️ Output
  My name is Deepak and I am 25 years old.                
              
            

Formatted Print using format() Method

              
  print("Name: {}, Age: {}".format("Deepak", 25))
  
  🖥️ Output
  Name: Deepak, Age: 25
              
            

eval() Function in Python

The eval() function is used to evaluate a string as a Python expression and return the result.

eval(expression) : expression → A string containing a valid Python expression

              
  x = 5
  result = eval("x + 10")
  print(result)   
  
  🖥️ Output : 15
              
            

Useful for Taking Expression Input from User

              
  exp = input("Enter expression: ")   # e.g., 2 + 3 * 4
  print("Result =", eval(exp))

  🖥️ Output
  Enter expression: 2 + 3 * 4
  Result = 14
              
            

Previous Next