Unit 1
Unit 1
Unit 1
Versions of Python
Python 1.x
Released: 1991
Key Features: Basic features like exception handling, functions, and the core data types (lists,
dictionaries, etc.) were introduced.
Python 2.x
Released: 2000
Key Features:
Introduced list comprehensions, garbage collection, and the yield statement.
Significant libraries and modules were added.
Unicode support was introduced but required a 'u' prefix.
Division of integers resulted in integer values (e.g., 5/2 = 2).
Python 3.x
Released: 2008
Key Features:
Print Function: The print statement was replaced with a print() function.
Integer Division: Division of integers now results in float values (e.g., 5/2 = 2.5).
Unicode: All strings are Unicode by default.
Iterators: Range and other iterating functions return iterators instead of lists.
Library Improvements: Many standard libraries were redesigned and improved.
Syntax Changes: Many syntactic features were changed or removed to make the language
cleaner and more consistent.
Key Differences Between Python 2.x and Python 3.x:
Python 2: Strings are ASCII (American Standard Code for Information Interchange) by
default, Unicode strings need a u prefix.
Python 3: Strings are Unicode by default.
Iterators:
Python 2: range(5) returns a list.
Python 3: range(5) returns a range object (iterator).
Library Changes:
Many standard libraries have been renamed or restructured in Python 3.
For example, ConfigParser in Python 2 is configparser in Python 3.
Syntax Changes:
Many deprecated functions and syntax from Python 2 were removed in Python 3.
Example: xrange() was removed in favor of range().
Features of Python
1. Easy to Read and Write: Python's syntax is clear and concise, making it an excellent
choice for beginners and experienced developers alike.
2. Interpreted Language: Python is executed line by line, which makes debugging easier
and code execution simpler.
3. Dynamically Typed: Python does not require explicit declaration of variable types,
making it flexible but also necessitating careful variable management.
4. Extensive Standard Library: Python comes with a vast standard library that supports
many common programming tasks, such as connecting to web servers, reading and
modifying files, and more.
5. Cross-Platform: Python programs can run on various operating systems, including
Windows, macOS, and Linux, without needing modification.
Data Science and Machine Learning: Libraries like NumPy, pandas, Scikit-learn, and
TensorFlow make Python a popular choice for data analysis, visualization, and machine
learning.
Automation and Scripting: Python is often used for writing scripts to automate repetitive tasks.
Software Development: Python can be used to develop standalone applications and prototype
software.
Game Development: Libraries like Pygame provide tools for game development.
Network Programming: Python has robust support for networking, enabling the development
of complex network applications.
The following window will open. Click on the Add Path check box, it will set the Python path
automatically otherwise you will have to do it explicitly, then click on Install Now. It will start
installing Python on Windows.
After installation is complete click on Close. Python is installed.
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 ".
Compilation: The interpreter compiles the AST into bytecode. Bytecode is an intermediate,
platform-independent representation of the source code. This bytecode is not machine code
but a lower-level code that the Python Virtual Machine (PVM) can execute.
Execution: The Python Virtual Machine (PVM) reads and executes the bytecode. The PVM
interprets the bytecode instructions and translates them into machine-level instructions as
needed, but this translation happens at runtime, not ahead of time.
{Assembly language is a low-level language that helps to communicate directly with computer
hardware. It uses mnemonics to represent the operations that a processor has to do. Which is
an intermediate language between high-level languages like C++ and the binary language. It
uses hexadecimal and binary values, and it is readable by humans.}
Python Virtual Machine (PVM): The PVM is an interpreter that executes the bytecode. It
reads the bytecode instructions and translates them into machine-level instructions on the
fly. This means the PVM acts as a middle layer between the bytecode and the machine code.
It also provides programming environment.
An Abstract Syntax Tree (AST) is a tree representation of the abstract syntactic structure of
source code. Each node in the tree represents a construct occurring in the source code. The tree
reflects the hierarchical structure of the program, showing the syntactic relationships between
different parts of the code.
1. Abstraction: The AST abstracts away certain details of the source code, such as
punctuation (e.g., commas, semicolons) and other tokens that do not affect the structure of
the code.
2. Hierarchy: The AST captures the hierarchical structure of the source code, making it
easier to analyze and manipulate.
3. Nodes: Each node in the AST represents a construct such as an expression, a statement, or
a block of code. Nodes can have children that represent sub-constructs.
Indentation
Indentation in Python is the use of whitespace (spaces or tabs) at the beginning of a line to
define the structure and organization of code. Unlike many other programming languages,
which use braces or keywords to delimit blocks of code, Python uses indentation levels to
indicate the grouping of statements.
Key Points About Indentation in Python
Block Structure: Indentation is used to define blocks of code. For example, the body of a
function, loop, or conditional statement is indented relative to the enclosing statement.
Consistency: The amount of indentation must be consistent within a block. Mixing spaces and
tabs or using inconsistent levels of indentation will result in an IndentationError.
Syntax Requirement: Indentation is not optional in Python; it is a part of the syntax. Incorrect
indentation will lead to syntax errors.
def greet(name):
if name:
print(f"Hello, {name}!")
else:
print("Hello, World!")
Indentation Rules
Python Keywords
Every language contains words and a set of rules that would make a sentence meaningful.
Similarly, in Python programming language, there are a set of predefined words, called
Keywords which along with Identifiers will form meaningful sentences when used together.
Python keywords cannot be used as the names of variables, functions, and classes.
Keywords in Python are reserved words that cannot be used as a variable name, function name,
or any other identifier.
List of Keywords in Python
Keyword Description Keyword Description Keyword Description
Represents an
and It is a Logical False expression that nonlocal It is a non-
Operator will result in not local variable
being true.
It is used to
as finally It is used with not It is a Logical
create an alias
exceptions Operator
name
pass is used
To import when the user
break Break out a from pass
specific parts of doesn’t
Loop
a module want any code
to execute
raise is used
It is used to
class It is used to global raise to raise
declare a
define a class exceptions or
global variable
errors.
Represents an
It is used to It is used to
def import True expression
define the import a
that will result
Function module
in true.
While Loop is
To check if a
Conditional used to
elif in value is present while
statements, execute a
in a Tuple, List,
same as else-if block of
etc.
statements
with
It is used in a Used to create statement is
else conditional lambda an anonymous with used in
statement function exception
handling
yield keyword
try-except is is used to
except None It represents a yield
used to handle create a
null value
these errors generator
function
Python Variables
Python Variable is containers that store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type.
A variable is created the moment we first assign a value to it. A Python variable is a name
given to a memory location. It is the basic unit of storage in a program.
Rules for Python variables
A Python variable name must start with a letter or the underscore character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).
Variable in Python names are case-sensitive (name, Name, and NAME are three different
variables).
The reserved words(keywords) in Python cannot be used to name the variable in Python.
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Arithmetic Operators
The Python operators are fundamental for performing mathematical calculations in
programming languages like Python, Java, C++, and many others. Arithmetic operators are
symbols used to perform mathematical operations on numerical values. In most
programming languages, arithmetic operators include addition (+), subtraction (-),
multiplication (*), division (/), and modulus (%).
Arithmetic Operators in Python
There are 7 arithmetic operators in Python. The lists are given below:
Operator Description Syntax
Assignment Operators
The Python Operators are used to perform operations on values and variables. These
are the special symbols that carry out arithmetic, logical, and bitwise computations.
The value the operator operates on is known as the Operand. Here, we will cover
Different Assignment operators in Python.
Sign Syntax
Operators Description
Python Equality
== Equal to: True if both operands are equal a == b
Operators
Inequality
!= Not equal to: True if operands are not equal a != b
Operators
Less than or Equal Less than or equal to: True if left operand is
<= a <= b
to Sign less than or equal to the right
Logical Operators
Python logical operators are used to combine conditional statements, allowing you to perform
operations based on multiple conditions. These Python operators, alongside arithmetic
operators, are special symbols used to carry out computations on values and variables.
In Python, Logical operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR, and Logical NOT operations.
Returns True if
or either of the x or y x<7 or x>15
operands is true
a = True
b = False
result4 = a and b # False, because both a and b need to be True
result5 = a or b # True, because at least one of a or b is True
result6 = not a # False, because a is True and not inverts it
print(result4) # Output: False
print(result5) # Output: True
print(result6) # Output: False
AND Operator in Python
The Boolean AND operator returns True if both the operands are True else it returns False.
Identity Operators
The Python Identity Operators are used to compare the objects if both the objects are
actually of the same data type and share the same memory location. There are different
identity operators such as:
Identity
Operator Description Syntax
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1
We can see here that even though both the lists, i.e., ‘lst1’ and ‘lst2’ have same data, the output
is still False. This is because both the lists refers to different objects in the memory. Where as
when we assign ‘lst3’ the value of ‘lst1’, it returns True. This is because we are directly giving
the reference of ‘lst1’ to ‘lst3’.
Python IS NOT Operator
The is not operator evaluates True if both variables on the either side of the operator are not
the same object in the memory location otherwise it evaluates False.
# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1
Slice Function
Syntax: slice(start, stop, step)
Parameters:
Bitwise Operators
Python bitwise operators are used to perform bitwise calculations on integers. The integers
are first converted into binary and then operations are performed on each bit or
corresponding pair of bits, hence the name bitwise operators. The result is then returned in
decimal format.
Note: Python bitwise operators work only on integers.
OPERATOR NAME DESCRIPTION SYNTAX