Unit-1
Overview of Python
History
• Python is one of the most popular, high-level, general-purpose
programming languages.
• Creator: Guido van Rossum
• Started: 1989, at Centrum Wiskunde & Informatica (CWI),
Netherlands
• First Release: 1991
• Reason: Started as a hobby project during Christmas holidays
• Named after the BBC comedy series “Monty Python’s Flying Circus”
• Guido wanted a name that was short, unique, and a little mysterious
• Python 1.0 was officially released on January 26, 1994, introducing
lambda functions and fundamental object-oriented support.
• Python 2.0 arrived in October 2000, bringing new features including
garbage collection, list comprehensions, and unicode support.
• Python 3.0, released in 2008, was a significant update that broke
backward compatibility to improve the language’s consistency and
usability
Features of Python
• 1. Free and Open Source
• 2. Easy to code
• 3. Easy to Read
• 4. Object-Oriented Language
• 5. GUI Programming Support
• 6. High-Level Language
• 7. Easy to Debug
• 8. Python is a Portable language
• 9. Interpreted Language
• [Link] Language
• 1. Free and Open Source: Python language is freely available at the
official website and you can download it from the given download link
below click on the Download Python keyword. Download
Python Since it is open-source, this means that source code is also
available to the public. So you can download it, use it as well as share
it.
• 2. Easy to code: Python is a high-level programming language. Python
is very easy to learn the language as compared to other languages like
C, C#, Javascript, Java, etc. It is very easy to code in the Python
language and anybody can learn Python basics in a few hours or days.
It is also a developer-friendly language.
• 3. Easy to Read: Python's syntax is really straightforward. The code
block is defined by the indentations rather than by semicolons or
brackets.
• 4. Object-Oriented Language: One of the key features of Python is
Object-Oriented programming. Python supports object-oriented
language and concepts of classes, object encapsulation, etc.
• 5. GUI Programming Support: Graphical User interfaces can be made
using a module such as PyQt5, PyQt4, wxPython, or Tk in Python.
PyQt5 is the most popular option for creating graphical apps with
Python.
• 6. High-Level Language: Python is a high-level language. When we
write programs in Python, we do not need to remember the system
architecture, nor do we need to manage the memory.
7. Easy to Debug: You will be able to quickly identify and correct the
majority of your program's issues once you understand how
to interpret Python's error traces.
[Link] is a Portable language: Python language is also a portable
language. For example, if we have Python code for Windows and if we
want to run this code on other platforms such as Linux, Unix, and Mac
then we do not need to change it, we can run this code on any
platform.
• 9. Interpreted Language: Python is an Interpreted Language because
Python code is executed line by line at a time. like other languages C,
C++, Java, etc. there is no need to compile Python code this makes it
easier to debug our code. The source code of Python is converted into
an immediate form called bytecode.
• [Link] Language: Python is also an Integrated language
because we can easily integrate Python with other languages like
C, C++, etc.
How to Install Python in Windows?
• Step 1: Select Version to Install Python
• Visit the official page for
Python [Link] on the Windows
operating system. Locate a reliable version of Python 3, preferably
version 3.10.11
• Choose the correct link for your device from the options provided:
either Windows installer (64-bit) or Windows installer (32-bit) and
proceed to download the executable file.
• Step 2: Downloading the Python Installer
• Once you have downloaded the installer, open the .exe file, such as
[Link], by double-clicking it to launch the
Python installer. Choose the option to Install the launcher for all users
by checking the corresponding checkbox, so that all users of the
computer can access the Python launcher [Link] users to
run Python from the command line by checking the Add [Link]
to PATH checkbox.
• After Clicking the Install Now Button the setup will start installing
Python on your Windows system. You will see a window like this.
• Step 3: Running the Executable Installer
• After completing the setup. Python will be installed on your Windows
system. You will see a successful message.
• Step 4: Verify the Python Installation in Windows
• Close the window after successful installation of Python. You can
check if the installation of Python was successful by using either the
command line or the Integrated Development Environment (IDLE)
• To access the command line, click on the Start menu and type "cmd"
in the search bar. Then click on Command Prompt.
• python --version
• Go to Start and enter IDLE in the search bar and then click
the IDLE app, for example, IDLE (Python 3.10.11 64-bit). If you can
see the Python IDLE window then you are successfully able to
download and installed Python on Windows.
Execution of Python program
Literals in python
• Literals in Python are fixed values written directly in the code that
represent constant data. They provide a way to store numbers, text,
or other
• Python supports different types of literals, such as numeric literals,
string literals, Boolean literals, and special values like None. For
example:
• 10, 3.14, and 5 + 2j are numeric literals.
• 'Hello' and "Python" are string literals.
• True and False are Boolean literals.
Numeric Literals
• Numeric literals represent numbers and are classified into three
types:
• Integer Literals – Whole numbers (positive, negative, or zero) without
a decimal point. Example: 10, -25, 0
• Floating-point (Decimal) Literals – Numbers with a decimal point,
representing real numbers. Example: 3.14, -0.01, 2.0
• Complex Number Literals – Numbers in the form a + bj, where a is
the real part and b is the imaginary part. Example: 5 + 2j, 7 - 3j
String Literals
• String literals are sequences of characters enclosed in quotes. They
are used to represent text in Python.
• Types of String Literals:
• Single-quoted strings – Enclosed in single quotes (' '). Example: 'Hello,
World!'
• Double-quoted strings – Enclosed in double quotes (" "). Example:
"Python is fun!"
• Triple-quoted strings – Enclosed in triple single (''' ''') or triple double
(""" """) quotes, generally used for multi-line strings or docstrings.
Boolean Literals
• Boolean literals represent truth values in Python. They help in
decision-making and logical operations.
• True – Represents a positive condition (equivalent to 1).
• False – Represents a negative condition (equivalent to 0).
Collection Literals
• Python provides four different types of literal collections:
• List literals: [1, 2, 3]
• Tuple literals: (1, 2, 3)
• Dictionary literals: {"key": "value"}
• Set literals: {1, 2, 3}
Python Variables
• In Python, variables are used to store data that can be referenced and
manipulated during program execution. A variable is essentially a
name that is assigned to a value.
• Unlike Java and many other languages, Python variables do not
require explicit declaration of type.
x=5
name = "Samantha"
print(x)
print(name)
• Rules for Naming Variables
• Variable names can only contain letters, digits and underscores (_).
• A variable name cannot start with a digit.
• Variable names are case-sensitive like myVar and myvar are different.
• Avoid using Python keywords like if, else, for as variable names.
• Assigning Values to Variables
• Variables in Python are assigned values using the = operator.
x=5
y = 3.14
z = "Hi"
Python Keywords and Identifiers
• Python Keywords are reserved words with fixed meanings that define
Python’s syntax. Cannot be used as names.
• Python has 35 keywords
• True, False, None,
and, or, not, is, in,if, else, elif, for, while, break, continue, pass, try, exc
ept, finally, raise, assert, def, return, lambda, yield, class, with, as,
import, from, global, nonlocal, async, await
Identifiers in Python
• Python Identifiers are user-defined names for variables, functions, or
classes. Must follow naming rules (no digits at start, only _ allowed).
• User-defined names for variables, functions, classes, modules, etc.
• Can include letters, digits, and underscores (_).
• Case-sensitive → num, Num, and NUM are different identifiers.
• Python provides [Link]() to check if a string is a valid identifier.
Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore (
_ ).
Examples of Python Identifiers
• Valid identifiers:
• var1
• _var1
• _1_var
• var_1
• Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1
Python Data Types
• Data types in Python are a way to classify data items.
Numeric Data Types
• Integers: value is represented by int class. It contains positive or
negative whole numbers (without fractions or decimals). There is no
limit to how long an integer value can be.
• Float: value is represented by float class. It is a real number with a
floating-point representation. It is specified by a decimal point.
• Complex Numbers: It is represented by a complex class. It is
specified as (real part) + (imaginary part)j. For example - 2+3j
a=5
print(type(a))
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
Input/Output Operations
With the print() function, we can display output in various formats,
while the input() function is used to take user input.
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output:
Enter your name: Swapna
Hello, Swapna ! Welcome!
Indentation in Python
• In Python, indentation is used to define blocks of code. Indentation is
achieved using whitespace (spaces or tabs) at the beginning of each
line.
if 10 > 5:
print("This is true!")
print("I am tab indentation")
print("I have no indentation")
Operators
• In Python, operators are special symbols or keywords that perform
operations on values and variables. There are 7 operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic Operators
• Arithmetic operators are used with numeric values to perform
common mathematical operations:
• # Arithmetic Operators
• a = 10
• b=3
print("Addition:", a + b) # Output: 13
• print("Subtraction:", a - b) # Output: 7
• print("Multiplication:", a * b) # Output: 30
• print("Division:", a / b) # Output: 3.3333333333333335
• print("Modulus:", a % b) # Output: 1
• print("Exponentiation:", a ** b) # Output: 1000
• print("Floor Division:", a // b) # Output: 3
Assignment Operators
• # Assignment Operators
• x=5
• print("Initial value of x:", x) # Output: 5
• print("After x += 3:", x) # Output: 8
• print("After x -= 2:", x) # Output: 6
• print("After x *= 4:", x) # Output: 24
• print("After x /= 3:", x) # Output: 8.0
• print("After x %= 5:", x) # Output: 3.0
• print("After x **= 2:", x) # Output: 9.0
• print("After x //= 3:", x) # Output: 3.0
Comparison Operators
• This operators are used to compare two values.
• # Comparison Operators
• x=5
• y = 10
• print("Equal:", x == y) # Output: False
• print("Not Equal:", x != y) # Output: True
• print("Greater Than:", x > y) # Output: False
• print("Less Than:", x < y) # Output: True
• print("Greater or Equal:", x >= y) # Output: False
• print("Less or Equal:", x <= y) # Output: True
Logical Operators
• Logical operators are used to combine conditional
statements:
• # Logical Operators
• a = True
• b = False
• print("Logical AND:", a and b) # Output: False
• print("Logical OR:", a or b) # Output: True
• print("Logical NOT:", not a) # Output: False
Identity Operators
• Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory
location:
• # Identity Operators
• a = [1, 2, 3]
•b=a
• c = [1, 2, 3]
• print("a is b:", a is b) # Output: True
• print("a is c:", a is c) # Output: False
• print("a is not c:", a is not c) # Output: True
• print("a == c:", a == c) # Output: True
Membership Operators
• Membership operators are used to test if a sequence is
presented in an object:
• # Membership Operators
• text = "Hello, World!"
• print("'H' in text:", 'H' in text) # Output: True
• print("'h' in text:", 'h' in text) # Output: False
• print("'World' not in text:", 'World' not in text) # Output: False
• print("'Python' not in text:", 'Python' not in text) # Output: True
Bitwise Operators
• Bitwise operators are used to compare (binary)
numbers:
• # Bitwise Operators
• a = 5 # Binary: 0101
• b = 3 # Binary: 0011
• print("Bitwise AND:", a & b) # Output: 1 (Binary: 0001)
• print("Bitwise OR:", a | b) # Output: 7 (Binary: 0111)
• print("Bitwise XOR:", a ^ b) # Output: 6 (Binary: 0110)
• print("Bitwise NOT:", ~a) # Output: 10 (Binary: 1010)
• print("Bitwise Left Shift:", a << 1) # Output: 10 (Binary: 1010)
• print("Bitwise Right Shift:", a >> 1) # Output: 2 (Binary: 0010)
Precedence and Associativity
• operator precedence determines the order in which operations are
evaluated in an expression. Operators with higher precedence are
evaluated before operators with lower precedence. When operators
have the same precedence, their associativity determines the order of
evaluation.
Precedence Operators Description Associativity
1 () Parentheses Left to right
2 ** Exponentiation Right to left
Unary plus, unary minus, bitwise
3 +x, -x, ~x Right to left
NOT
Multiplication, matrix mult, division,
4 *, @, /, //, % Left to right
floor division, remainder
5 +, - Addition and subtraction Left to right
6 <<, >> Bitwise shifts Left to right
7 & Bitwise AND Left to right
8 ^ Bitwise XOR Left to right
9 | Bitwise OR Left to right
<, <=, >, >=, !=, ==, is, is not,
10 Comparison, identity, membership Left to right
in, not in
11 not x Boolean NOT Right to left
12 and Boolean AND Left to right
13 or Boolean OR Left to right
Expressions
• An expression is a combination of values, variables, operators, and
calls to functions. Expressions need to be evaluated. If you ask python
to print an expression, the interpreter evaluates the expression and
displays the result.
• Ex:
• X=10
• Y=20
• Print x+y
result = 2 + 3 * 4 ** 2 - 8 / 2
print(result)
Multiplication (*), division (/), and exponentiation (**) have higher
precedence than addition (+) and subtraction (-), so 4 ** 2 evaluates to
16 first, then 3 * 16 = 48, 8 / 2 = 4, and finally 2 + 48 - 4 = 46.
Parentheses can override this order, such as (2 + 3) * (4 ** 2 - 8 / 2).
Examples
Control Structures
• A control statement is a statement that determines the control flow of a set of
instructions, i.e., it decides the sequence in which the instructions in a program are to
be executed.
• Types of Control Statements —
• Sequential Control: A Python program is executed sequentially from the first line of
the program to its last line.
• Selection Control: To execute only a selected set of statements.
• Iterative Control: To execute a set of statements repeatedly.
Conditional Statements(If Statement)
If-Else Statement
Nested if Statements
• A statement that contains other statements is called a compound
statement. Nested if statements are used to check if more than one
conditions are satisfied.
If-elif-else Statement
Type Conversion(Explicit)
Type conversion means manually converting one data type into another using
built-in functions.
1. x = "10"
y = int(x)
print(y) # 10
print(type(y)) # <class 'int’>
2.a = 5
b = str(a)
print(b) # "5"
print(type(b)) # <class 'str'>
n=7
f = float(n)
print(f) # 7.0
This is also called explicit type casting.
Type Coercion in Python (Implicit)
Type coercion means automatic conversion of one data type into
another by Python itself.
a = 10 # int
b = 2.5 # float
c=a+b
print(c) # 12.5
print(type(c)) # <class 'float'>
x=5
y = True
print(x + y) # 6
• Python does NOT do unsafe coercion.
Example:
a = 10
b = "5"
print(a + b) # TypeError
Correct way:
print(a + int(b)) # 15