0% found this document useful (0 votes)
8 views31 pages

Python Notes

Uploaded by

Karan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views31 pages

Python Notes

Uploaded by

Karan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT -1 PYTHON

Introduction to Python
Python is a high-level, interpreted, general-purpose programming language
created by Guido van Rossum in 1991. It is widely used because of its
simplicity, readability, and versatility. Python’s syntax is similar to natural
language, making it easy to learn even for beginners.
# Key Features of Python
1. Easy to Learn & Readable – Python code is clean and close to English.
2. Interpreted Language – No need for compilation; code runs directly.
3. Cross-platform – Works on Windows, Linux, macOS, and more.
4. Open Source – Free to use and supported by a large community.
5. Object-Oriented & Procedural – Supports multiple programming
paradigms.
6. Extensive Libraries – Comes with built-in modules and third-party
packages.
7. Dynamic Typing – No need to declare variable types explicitly.
# Popular Uses of Python
• Web Development (using Django, Flask)
• Data Science & Machine Learning (with Pandas, NumPy, TensorFlow)
• Automation & Scripting
• Game Development (Pygame)
• Desktop Applications (Tkinter, PyQt)
• Cybersecurity & Ethical Hacking
• Artificial Intelligence (AI) & Deep Learning

1
Example
# Simple Python Program
print("Hello, World!")

# Taking user input


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

# Limitations of Python
1. Speed Limitations
o Python is an interpreted language, so it runs slower compared to
compiled languages like C, C++ or Java.
o Not suitable for applications where high performance and speed
are critical (e.g., real-time systems, heavy 3D games).
2. Memory Consumption
o Python uses more memory because of its high-level data types
and dynamic typing.
o Not ideal for applications where memory optimization is crucial
(e.g., embedded systems, mobile apps).
3. Mobile & Game Development Weakness
o Python is rarely used for mobile app development (Android/iOS).
o Libraries for game development exist (like Pygame), but it is not as
powerful as C++ or Unity (C#).
4. Runtime Errors (Dynamically Typed)
o Because Python doesn’t require variable types to be declared,
errors may only show up during execution, not at compile-time.
o This can cause issues in large projects.

2
5. Database Access Limitations
o Python’s database access layers are weaker compared to Java
(JDBC) or C# (.NET).
o Not always the first choice for large enterprise applications
needing complex database operations.
6. Global Interpreter Lock (GIL)
o Python’s GIL allows only one thread to execute at a time.
o This limits multi-threading performance in CPU-heavy tasks.
7. Less Suitable for Low-Level Programming
o Python is a high-level language, so it is not suitable for low-level
system programming (like writing device drivers or operating
systems).

Major Applications of Python

1. Web Development

o Frameworks: Django, Flask, Pyramid


o Used to build websites and web applications (e.g., Instagram,
Pinterest).

2. Data Science & Data Analysis

o Libraries: Pandas, NumPy, Matplotlib, Seaborn


o Used for handling big data, statistics, and visualization.

3. Artificial Intelligence (AI) & Machine Learning (ML)


o Libraries: TensorFlow, PyTorch, Scikit-learn, Keras
o Used in predictive models, recommendation systems, and
robotics.

4. Automation & Scripting

3
o Used for automating repetitive tasks like file handling, web
scraping, and testing.

5. Game Development

o Library: Pygame
o Used to create simple 2D games and prototypes.

6. Desktop Applications

o Libraries: Tkinter, PyQt, Kivy


o Used for building GUI-based software and tools.

7. Networking & Cybersecurity

o Libraries: Scapy, Paramiko


o Used for penetration testing, network automation, and ethical
hacking.

8. Scientific & Numeric Computing

o Libraries: SciPy, SymPy


o Used in research, simulations, and complex mathematical
calculations.

9. Cloud Computing & DevOps

o Supported in tools like AWS Boto3, Ansible, Docker scripts.

10.Internet of Things (IoT)

o Libraries: MicroPython, PySerial


o Used for programming microcontrollers and IoT devices

# Python differences from other languages.


1. Syntax and Readability
• Python uses indentation instead of braces {} or keywords to define code
blocks.
4
• Its syntax is closer to natural English, making it more readable than
languages like C, C++, or Java.
• Example:
• if x > 10:
• print("Large number")
(No semicolons, no braces – unlike Java or C.)

2. Typing System
• Python is dynamically typed – you don’t need to declare variable types
explicitly.
• Languages like C, C++, and Java are statically typed – you must specify
data types.
• Example:
• x = 10 # integer
• x = "Hello" # string, no error

3. Compilation vs Interpretation
• Python is an interpreted language (executed line by line).
• C, C++, and Java are usually compiled (translated to machine
code/bytecode before execution).
• This makes Python slower, but easier for rapid development.

4. Memory Management
• Python uses automatic garbage collection.
• In C/C++, memory management must often be handled manually with
malloc() and free().

5
• Java also has garbage collection, but Python’s memory management is
more hidden from the programmer.

5. Libraries and Ecosystem

• Python has a massive ecosystem of libraries (e.g., NumPy, Pandas,


TensorFlow, Django).
• Other languages like C++ or Java also have libraries, but Python’s are
often easier to use and install.

6. Use Cases
• Python: Popular for data science, machine learning, web development,
scripting, AI, and automation.
• Java: More common in enterprise applications, Android development.
• C/C++: Used in system programming, embedded systems, game
engines.
• JavaScript: Dominates web frontend development.

7. Execution Speed
• Python is generally slower than C/C++ or Java because it’s interpreted
and dynamically typed.
• But Python trades speed for development speed and ease of use.

8. Community and Learning Curve

• Python has a beginner-friendly learning curve.


• Languages like C++ have steep learning curves (pointers, memory
management, complex syntax).
• Python’s community support and resources are very strong

6
Python Data Types

Data types in Python are a way to classify data items. They represent
the kind of value, which determines what operations can be performed
on that data. Since everything is an object in Python programming,
Python data types are classes and variables are instances (objects) of
these classes.
The following are standard or built-in data types in Python:
• Numeric: int, float, complex
• Sequence Type: string, list, tuple
• Mapping Type: dict
• Boolean: bool
• Set Type: set, frozenset
• Binary Types: bytes, bytearray, memoryview

1. Numeric Data Types


Python numbers represent data that has a numeric value. A numeric value can
be an integer, a floating number or even a complex number. These values are
defined as int, float and complex classes
• 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.
Optionally, character e or E followed by a positive or negative integer
may be appended to specify scientific notation.
• Complex Numbers: It is represented by a complex class. It is specified as
(real part) + (imaginary part)j. For example - 2+3j

Eg..
a=5
print(type(a))
7
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))

Output:
<class 'int'>
<class 'float'>
<class 'complex'>
2. Sequence Data Types
A sequence is an ordered collection of items, which can be of similar or
different data types. Sequences allow storing of multiple values in an organized
and efficient fashion. There are several sequence data types of Python:
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python,
there is no character data type, a character is a string of length one. It is
represented by str class.
List Data Type
Lists are similar to arrays found in other languages. They are an ordered and
mutable collection of items. It is very flexible as items in a list do not need to
be of the same type.

Eg..
# Empty list
a = []
# list with int values
a = [1, 2, 3]
print(a)
8
# list with mixed values int and String
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

Output:
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]

Tuple Data Type


Tuple is an ordered collection of Python objects. The only difference between a
tuple and a list is that tuples are immutable. Tuples cannot be modified after it
is created.

3. Boolean Data Type in Python


Python Boolean Data type is one of the two built-in values, True or False.
Boolean objects that are equal to True are truthy (true) and those equal to
False are falsy (false).

Eg..
print(type(True))
print(type(False))
print(type(true))

4. Set Data Type in Python


In Python Data Types, Set is an unordered collection of data types that is
iterable, mutable, and has no duplicate elements. The order of elements in a
set is undefined though it may consist of various elements.
# initializing empty set

9
s1 = set()

Eg..
s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])


print("Set with the use of List: ", s2)

Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}

5. Dictionary Data Type


A dictionary in Python is a collection of data values, used to store data values
like a map, unlike other Python Data Types, a Dictionary holds a key: value pair.
Key-value is provided in dictionary to make it more optimized. Each key-value
pair in a Dictionary is separated by a colon : , whereas each key is separated by
a ‘comma’.

Eg..
# initialize empty dictionary
d = {}
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)
# creating dictionary using dict() constructor
d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

10
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Python Operators
In Python programming, Operators in general are used to perform operations
on values and variables. These are standard symbols used for logical and
arithmetic operations. In this article, we will look into different types of Python
operators.
• OPERATORS: These are the special symbols. Eg- + , * , /, etc.
• OPERAND: It is the value on which the operator is applied.

Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication and division.
Eg..
# Variables
a = 15

11
b=4
# Addition
print("Addition:", a + b)
# Subtraction
print("Subtraction:", a - b)
# Multiplication
print("Multiplication:", a * b)
# Division
print("Division:", a / b)
# Floor Division
print("Floor Division:", a // b)
# Modulus
print("Modulus:", a % b)
# Exponentiation
print("Exponentiation:", a ** b)

Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625

12
# Comparison Operators
In Python, Comparison (or Relational) operators compares values. It either
returns True or False according to the condition.
Eg..
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
Logical Operators
Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
13
Example
a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False

# Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These
are used to operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Example
a = 10
b=4

print(a & b)
14
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output
0
14
-11
14
2
40
# Assignment Operators
Python Assignment operators are used to assign values to the variables. This
operator is used to assign the value of the right side of the expression to the
left side operand.
Example
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a

15
print(b)
b <<= a
print(b)

Output
10
20
10
100
102400

Loops and Control Statements (continue, break and pass) in


Python
Python supports two types of loops: for loops and while loops. Alongside these
loops, Python provides control statements like continue, break, and pass to
manage the flow of the loops efficiently. This article will explore these concepts
in detail.

for Loops
A for loop in Python is used to iterate over a sequence (such as a list, tuple,
string, or range).
Eg..
# Iterating over a list
a = [1, 2, 3]
for i in a:
print(i)

16
Output
1
2
3

while Loops
A while loop in Python repeatedly executes a block of code as long as a given
condition is True.

Eg..
# Using while loop
cnt = 0
while cnt < 5:
print(cnt)
cnt += 1

Output
0
1
2
3
4
# Control Statements in Loops
Control statements modify the loop's execution flow. Python provides three
primary control statements: continue, break, and pass.
break Statement

17
The break statement is used to exit the loop prematurely when a certain
condition is met.
# Using break to exit the loop
for i in range(10):
if i == 5:
break
print(i)

Output
0
1
2
3
4
# continue Statement
The continue statement skips the current iteration and proceeds to the next
iteration of the loop.
# Using continue to skip an iteration
for i in range(10):
if i % 2 == 0:
continue
print(i)

Output
1
3

18
5
7
9
pass Statement
The pass statement is a null operation; it does nothing when executed. It's
useful as a placeholder for code that you plan to write in the future.
# Using pass as a placeholder
for i in range(5):
if i == 3:
pass
print(i)

Output
0
1
2
3
4

1. Conditional Statements (Decision Making)


Used to make choices based on conditions.
• if statement

Eg..
x = 10
if x > 5:

19
print("x is greater than 5")

• if-else statement

Eg..
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")

• if-else-if ladder

Eg..
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")

What are Keywords?


• Keywords are reserved words in Python.
• They have special meaning and are part of the Python syntax.

20
• You cannot use them as identifiers (variable names, function names,
class names).

Categories of Keywords

1. Boolean Values
o True, False, None
2. Conditional & Looping
o if, elif, else, for, while, break, continue, pass
3. Exception Handling
o try, except, finally, raise, assert
4. Function & Class Related
o def, return, lambda, class, yield
5. Variable Scope & Namespace
o global, nonlocal
6. Import & Context
o import, from, as, with
7. Logical & Comparison
o and, or, not, is, in
8. Async Programming (advanced)
o async, await

What are Identifiers?

• Identifiers are the names you give to variables, functions, classes,


modules, or other objects in Python.
• They act like labels to identify pieces of data or code.

21
Example:
x = 10 # here, "x" is an identifier
name = "Rohit" # "name" is an identifier
def add(a, b): # "add" is an identifier for a function
return a + b

Rules for Identifiers in Python

1. Can contain letters (A–Z, a–z), digits (0–9), and underscore _.


2. Cannot start with a digit.

o num1, _value

o 1num (invalid)
3. Cannot use keywords as identifiers (like if, class, for).

o if = 10 → invalid

4. Case-sensitive:
o name and Name are two different identifiers.
5. No special symbols allowed (@, $, %, #, etc.).

What is a Statement in Python?

A statement is an instruction that the Python interpreter can execute.


• It tells Python what to do (like assign a value, run a loop, call a function).
• Python programs are basically made up of a sequence of statements.

Example:

• x = 5 # assignment statement
• print(x) # function call statement

22
Types of Statements in Python
1. Expression Statements
• Any expression that produces a value.
x = 10 + 5 # assignment is also an expression
print(x)
2. Assignment Statements
• Used to assign values to variables.
name = "Rohit"
marks = 95
3. Conditional Statements
• Used for decision-making (if, elif, else).
if marks >= 50:
print("Pass")
else:
print("Fail")
4. Looping Statements
• Used for repetition (for, while).
for i in range(3):
print("Hello")
5. Control Flow Statements
• Change the normal execution flow.
for i in range(5):
if i == 3:
break # exit loop
print(i)

23
6. Function / Class Definition Statements
def greet():
print("Welcome")

class Student:
pass
7. Import Statements
import math
from datetime import date

Simple vs Compound Statements


• Simple statements → written in a single line (e.g., assignment, print,
return).
x=5
print(x)
• Compound statements → consist of a header + indented block (e.g., if,
for, while, def, class).
if x > 0:
print("Positive")
else:
print("Negative")

What is Indentation?

• Indentation means the spaces or tabs at the beginning of a line of code.


• In Python, indentation is not optional – it is part of the syntax.

24
• It tells Python which block of code belongs to which statement.

Example of Indentation
if True:
print("This is indented") # belongs to 'if'
print("Still inside if")
print("Outside if") # not indented, outside block

Output:

This is indented
Still inside if
Outside if

What is Documentation?
• Documentation is written text that explains what your code does, how it
works, and how to use it.
• It helps you and others understand your program later.
• In Python, documentation can be written as:
1. Comments (#)
2. Docstrings (""" """)
3. External documents (README, manuals, API docs)

1. Comments (Inline Documentation)


• Start with #
• Explain a single line or block of code
• Ignored by Python interpreter
# This function adds two numbers
def add(a, b):
return a + b # returns the sum

2. Docstrings (Documentation Strings)


• Written inside triple quotes (""" or ''').
• Describe functions, classes, and modules.
• Can be accessed using the help() function or .__doc__.
Example:

25
def multiply(a, b):
"""This function multiplies two numbers and returns the result."""
return a * b

print(multiply.__doc__)
Output:
This function multiplies two numbers and returns the result.

3. Module & Class Docstrings


"""Math utilities module for basic operations."""

class Calculator:
"""Simple calculator class with add and subtract methods."""

def add(self, x, y):


"""Return the sum of x and y."""
return x + y

4. Accessing Documentation
• Using help():
help(multiply) # shows function documentation
• Using .doc:
print(Calculator.__doc__)

What is a Variable?
• A variable is a name that refers to a value stored in memory.
• It acts like a label for data that your program can use and manipulate.
• Variables do not need explicit declaration in Python — they are created
when you assign a value.

Creating Variables
x = 10 # integer variable
name = "Rohit" # string variable
marks = 95.5 # float variable

Rules for Variable Names


1. Must start with a letter (a–z, A–Z) or underscore (_)
o age, _value
o 1name → invalid

26
2. Can contain letters, digits, and underscores
o student1, total_marks
3. Cannot use Python keywords
o if = 10 → invalid
4. Case-sensitive
o Name and name are different variables
5. No spaces or special symbols
o total-marks → invalid

Assigning Values
# Single assignment
x=5

# Multiple assignment
a, b, c = 1, 2, 3

# Same value to multiple variables


x=y=z=0

Changing Variable Values


Variables are dynamic in Python — type can change:
x = 10 # integer
x = "Hello" # now string

Variable Types (Common Ones)


Type Example
int x = 10
float y = 3.14
str name = "Rohit"
bool flag = True
list numbers = [1, 2, 3]
tuple point = (5, 10)
dict student = {"name":"Rohit"}
set s = {1, 2, 3}

27
What is Multiple Assignment?
• Multiple assignment allows you to assign values to multiple variables in
a single line.
• It makes code cleaner and shorter.

Types of Multiple Assignment

1. Assigning multiple variables at once


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

Here:
• x gets 10
• y gets 20
• z gets 30

2. Assigning the same value to multiple variables


a=b=c=0
print(a, b, c) # 0 0 0
• All three variables point to the same value.

3. Swapping values (Pythonic way)


x=5
y = 10
x, y = y, x

28
print(x, y) # 10 5
• No need for a temporary variable.
• Python automatically unpacks the values.

4. Unpacking a list or tuple


numbers = [1, 2, 3]
x, y, z = numbers
print(x, y, z) # 1 2 3
• Works with tuples, lists, or any iterable.

Advantages of Multiple Assignment

1. Shorter and cleaner code.


2. Easy swapping of variables.
3. Easy unpacking of data structures.

What is Conversion?

• Type conversion is the process of converting one data type into another.
• Python supports implicit (automatic) and explicit (manual) conversion.
• Example:
• x = 5 # int
• y = 3.2 # float
• z = x + y # int + float → float
• print(z) # 8.2
• print(type(z)) # <class 'float'>

2. Explicit Type Conversion (Type Casting)


• You manually convert one data type to another using built-in functions
like int(), float(), str(), etc.

29
Examples:
a) Convert float to int
num = 9.8
print(int(num)) # 9
b) Convert int to float
x = 10
print(float(x)) # 10.0
c) Convert number to string
x = 20
print(str(x)) # "20"
d) Convert string to int
s = "50"
print(int(s)) # 50
e) Convert string to float
s = "3.14"
print(float(s)) # 3.14

3. Other Conversion Functions

Function Description

int(x) Converts x to integer

float(x) Converts x to float

str(x) Converts x to string

bool(x) Converts x to boolean (True/False)

list(x) Converts iterable x to list

30
Function Description

tuple(x) Converts iterable x to tuple

set(x) Converts iterable x to set

31

You might also like