Introduction to Python
Python is a high-level, interpreted, and general-purpose programming language.
• High-level → You don’t need to worry about complex details like memory
management.
• Interpreted → Python code runs line by line. You don’t compile it separately.
• Cross-platform → It works on Windows, macOS, and Linux.
• Versatile → Python is used for web development, artificial intelligence, data science,
game development, and automation.
Creator: Guido van Rossum (released in 1991).
Why Python?
Python has become one of the most widely used programming languages in the world.
Some main reasons are:
1. Simple and Easy to Learn
• Python syntax is close to English.
• Example:
• print("Hello, World!")
Much shorter and easier in Python.
2. Interpreted and Portable
• You don’t need to compile. Just run directly.
• The same code can run on Windows, Mac, Linux without changes.
3. Open Source and Free
• Anyone can download and use Python free of cost.
4. Huge Library Support
• Python has built-in libraries and external modules for almost everything (math, data
science, web, ML, etc.).
• Example: math, numpy, pandas, django, flask, tensorflow.
5. Multi-purpose Language
• Can be used for web development, automation, AI, data analysis, game
development, desktop apps, scientific computing, etc.
6. Community Support
• Millions of developers worldwide. Easy to find tutorials, documentation, and help.
Applications of Python
Python is a general-purpose language, meaning it is not limited to one type of project.
1. Web Development
• Frameworks: Django, Flask, FastAPI
• Example: Instagram, Pinterest, and Spotify use Python for backend.
2. Data Science and Analytics
• Libraries: NumPy, Pandas, Matplotlib, Seaborn
• Used for analyzing large datasets, visualizing graphs, and finding patterns.
3. Artificial Intelligence (AI) and Machine Learning (ML)
• Libraries: TensorFlow, PyTorch, Scikit-learn, OpenCV
• Used in chatbots, recommendation systems (like YouTube, Netflix), image
recognition, self-driving cars, etc.
4. Automation (Scripting)
• Python is excellent for automating boring/repetitive tasks.
• Example:
o Auto-fill forms
o Rename multiple files
o Send emails automatically
o Scrape data from websites
5. Game Development
• Library: Pygame
• Used to build 2D/3D games.
6. Desktop Applications
• Libraries: Tkinter, PyQt, Kivy
• Used to make GUI applications (calculator apps, note apps, etc.).
7. Networking & Cybersecurity
• Python is widely used in penetration testing, writing hacking tools, and network
automation.
• Example libraries: scapy, paramiko.
8. Embedded Systems & IoT
• Python can run on microcontrollers using MicroPython or Raspberry Pi.
• Used for smart devices, sensors, and robotics.
9. Scientific Computing & Research
• Used in mathematics, physics, chemistry, biology simulations.
• Libraries: SciPy, SymPy, BioPython.
10. Big Companies Using Python
• Google → Uses Python for internal tools & APIs.
• Netflix → Recommendation engine.
• NASA → Uses Python in space research.
• Dropbox → Entire backend originally built in Python.
Python Variables
A variable is a name that stores a value in memory.
• Variables act like containers or labels for data.
• Python decides the type automatically (dynamic typing).
Example:
x = 10 # integer
name = "hello" # string
pi = 3.14 # float
A variable can change its type during execution:
a = 100 # int
a = "Hello" # str (changed type)
Rules for Variables
When naming variables, follow these rules:
Valid Examples:
• Start with a letter or underscore _
• Can contain letters, digits, and underscores
• Case-sensitive (name ≠ Name)
Invalid Examples:
• Cannot start with a number
• Cannot contain spaces or special characters like @, $, %
• Cannot use Python keywords
_valid = 100 # valid
name1 = "Ritik" # valid
Name = "Dwivedi" # valid (different from 'name')
1name = "Hi" # invalid (starts with number)
my-name = "abc" # invalid (hyphen not allowed)
for = 5 # invalid (keyword)
Identifiers
An identifier is the name used to identify variables, functions, classes, modules, etc.
Examples:
x = 10 # x → variable identifier
def add(a, b): # add → function identifier
return a+b
class Student: # Student → class identifier
pass
Identifiers follow the same rules as variable names.
Keywords
Keywords are reserved words in Python with special meaning.
Cannot be used as identifiers/variables.
Examples: if, else, for, while, class, def, True, False, None.
To see keywords in Python:
import keyword
print([Link])
Common Keywords (Python 3.x):
False None True and as assert
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
Naming Conventions & Styles
Python doesn’t force a strict style, but developers follow common conventions:
snake_case (recommended by PEP 8)
• All lowercase, words separated by underscore.
• Common for variables and functions.
student_name = "rahul"
total_marks = 95
def calculate_total(): ...
camelCase
• First word lowercase, next words start with uppercase letter.
• Sometimes used in variables/functions (especially in mixed projects with JavaScript).
studentName = "Rahul"
totalMarks = 95
def calculateTotal(): ...
PascalCase
• Each word starts with uppercase.
• Commonly used for class names.
class StudentDetails: ...
UPPERCASE
• Used for constants.
PI = 3.14159
MAX_LIMIT = 1000
Indentation in Python
Unlike C, C++, or Java where { } are used to define blocks, Python uses indentation
(spaces/tabs).
• Indentation = the spaces before a line of code.
• Required to tell Python which statements belong together.
By default, 4 spaces are recommended (PEP 8).
Example:
if True:
print("This is indented") # inside if block
print("Still inside block")
print("Outside block") # no indentation
If you forget indentation, Python throws an IndentationError:
Blocks in Python
A block is a group of statements executed together.
In Python, blocks are defined only by indentation level.
Examples of blocks:
• Block of an if statement
• Block of a for/while loop
• Block of a function
• Block of a class
Example (If Block):
if 10 > 5:
print("10 is greater")
print("This is inside the block")
print("This is outside") # not part of block
Example (Function Block):
def greet(name):
print("Hello", name) # function block
print("Welcome!") # same block
Local Scope
Variables defined inside a function → accessible only inside that function.
def my_func():
x = 10 # local variable
print(x)
my_func()
print(x) # Error: x not defined outside
Global Scope
Variables defined outside all functions → accessible everywhere.
x = 100 # global variable
def my_func():
print(x) # accessible inside
my_func()
print(x) # accessible outside
global Keyword
If you want to modify a global variable inside a function, use global.
x = 50
def update():
global x
x = 100
update()
print(x) # 100
Python Data Types
In Python, everything is treated as an object. A data type defines the kind of value a variable
can hold and what operations can be performed on that value. Unlike languages like C or
Java, Python is dynamically typed, which means you don’t have to explicitly declare the data
type of a variable—Python automatically determines it when you assign a value.
1. Numeric Data Types
Python has several built-in numeric types used to store numbers.
a) Integers (int)
• Whole numbers (positive, negative, or zero) without decimal points.
• Example:
• x = 10
• y = -34
• z=0
• Python integers have unlimited precision, meaning they can store very large
numbers (unlike C/Java where integer size is fixed).
b) Floating-point numbers (float)
• Numbers with decimal points or in exponential form.
• Example:
• pi = 3.14
• g = -9.81
• e = 2.5e3 # 2500.0 in scientific notation
c) Complex numbers (complex)
• Numbers with a real and imaginary part.
• Written as a + bj where j is the imaginary unit.
• Example:
• c1 = 2 + 3j
• c2 = 5j
• print([Link]) # 2.0
• print([Link]) # 3.0
2. Boolean Type (bool)
• Represents True or False values.
• Internally, True = 1 and False = 0.
• Used for decision-making and conditions.
• Example:
• isActive = True
• isAdmin = False
• print(5 > 2) # True
3. Sequence Data Types
These are ordered collections of items. They allow indexing, slicing, and iteration.
a) Strings (str)
• A sequence of characters enclosed in single, double, or triple quotes.
• Strings are immutable (cannot be changed once created).
• Example:
• name = "Rahul"
• message = 'Python is fun'
• paragraph = """This is
• a multi-line string."""
• String operations:
• s = "Python"
• print(s[0]) #P
• print(s[-1]) #n
• print(s[0:3]) # Pyt
• print([Link]()) # PYTHON
b) Lists (list)
• An ordered, mutable collection of items (can store mixed data types).
• Defined using square brackets [].
• Example:
• fruits = ["apple", "banana", "cherry", 10, 5.5]
• fruits[1] = "mango" # Lists are mutable
c) Tuples (tuple)
• Similar to lists but immutable (cannot be changed).
• Defined using parentheses ().
• Example:
• coordinates = (10, 20)
• colors = ("red", "green", "blue")
d) Range (range)
• Represents a sequence of numbers (often used in loops).
• Example:
• for i in range(1, 6):
• print(i) # 1 2 3 4 5
4. Set Data Types
• Unordered collections of unique items.
• Mutable, but elements must be immutable (no lists/dicts inside sets).
• Example:
• numbers = {1, 2, 3, 3, 4}
• print(numbers) # {1, 2, 3, 4}
• [Link](5)
• [Link](2)
• Special type: Frozen Set (frozenset) → Immutable set.
5. Dictionary (dict)
• Stores data in key-value pairs.
• Keys must be unique and immutable.
• Values can be of any type.
• Example:
• student = {
• "name": "Ritik",
• "age": 22,
• "skills": ["Python", "MERN", "AI"]
• }
• print(student["name"]) # Ritik
• student["age"] = 23 # update value
6. None Type
• Represents the absence of a value.
• Example:
• result = None
• print(result) # None
Type Casting (Conversion between Data Types)
Python allows changing one data type to another.
x = "100"
y = int(x) # convert string to int
z = float(y) # convert int to float
print(type(z)) # <class 'float'>
Python Operators
In Python, operators are special symbols or keywords used to perform operations on
variables and values. For example, + adds numbers, * multiplies, == checks equality, etc.
Operators work on operands (the data).
Example: In 5 + 3, 5 and 3 are operands, and + is the operator.
1. Arithmetic Operators
Used for basic mathematical calculations.
Operator Meaning Example Result
+ Addition 5+3 8
- Subtraction 10 - 4 6
* Multiplication 6*2 12
Operator Meaning Example Result
/ Division (float) 7/2 3.5
// Floor Division 7 // 2 3
% Modulus (remainder) 7 % 2 1
** Exponent (power) 2 ** 3 8
2. Relational (Comparison) Operators
Used to compare values. The result is always True or False.
Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 7>4 True
< Less than 2<5 True
>= Greater or equal 4 >= 4 True
<= Less or equal 3 <= 6 True
Example:
x, y = 10, 20
print(x > y) # False
print(x <= y) # True
3. Logical Operators
Used to combine conditions.
Operator Meaning Example Result
and True if both are true (5 > 2 and 7 > 3) True
or True if at least one is true (5 > 10 or 7 > 3) True
Operator Meaning Example Result
not Reverses condition not(5 > 2) False
Example:
x=5
print(x > 0 and x < 10) # True
print(x > 10 or x == 5) # True
print(not(x == 5)) # False
4. Assignment Operators
Used to assign values to variables.
Operator Example Meaning
= x=5 Assign 5 to x
+= x += 3 x=x+3
-= x -= 2 x=x-2
*= x *= 4 x=x*4
/= x /= 3 x=x/3
//= x //= 2 x = x // 2
%= x %= 2 x=x%2
**= x **= 3 x = x ** 3
Example:
x = 10
x += 5 # x = 15
x *= 2 # x = 30
print(x)
5. Bitwise Operators
Work at the binary level on numbers.
Operator Meaning Example Result
& AND 5&3 1
` ` OR `5
^ XOR 5^3 6
~ NOT (invert) ~5 -6
<< Left shift 5 << 1 10
>> Right shift 5 >> 1 2
Example:
a, b = 5, 3 # binary: 101 and 011
print(a & b) # 1 (001)
print(a | b) # 7 (111)
print(a ^ b) # 6 (110)
print(~a) # -6
print(a << 1) # 10
print(a >> 1) # 2
6. Membership Operators
Check if a value exists in a sequence.
Operator Example Result
in "a" in "apple" True
not in "x" not in "apple" True
Example:
fruits = ["apple", "mango", "banana"]
print("apple" in fruits) # True
print("grapes" not in fruits) # True
7. Identity Operators
Check if two variables point to the same object in memory (not just same value).
Operator Example Result
is x is y True if x and y are same object
is not x is not y True if x and y are different objects
Example:
x = [1, 2, 3]
y=x
z = [1, 2, 3]
print(x is y) # True (same object)
print(x is z) # False (same value, different object)
print(x == z) # True (values equal)
8. Operator Precedence
When multiple operators are used in a single expression, precedence decides which is
evaluated first.
Precedence (High → Low) Operators
1 () Parentheses
2 ** Exponentiation
3 +x, -x, ~x Unary operators
4 *, /, //, %
5 +, -
6 <<, >>
7 &
8 ^
Precedence (High → Low) Operators
9 `
10 Comparisons (==, >, <, !=, >=, <=)
11 not
12 and
13 or
Example:
print(2 + 3 * 4) # 14 (multiplication before addition)
print((2 + 3) * 4) # 20 (parentheses change order)