0% found this document useful (0 votes)
12 views37 pages

Python Programming Unit 1 Overview

The document provides an introduction to Python programming, covering its history, installation, syntax, data types, and control flow. It highlights Python's readability, versatility, and extensive libraries, making it suitable for various applications. Key topics include variable management, basic data types, and the importance of indentation and naming conventions in Python programming.

Uploaded by

biranjesujal
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)
12 views37 pages

Python Programming Unit 1 Overview

The document provides an introduction to Python programming, covering its history, installation, syntax, data types, and control flow. It highlights Python's readability, versatility, and extensive libraries, making it suitable for various applications. Key topics include variable management, basic data types, and the importance of indentation and naming conventions in Python programming.

Uploaded by

biranjesujal
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

lOMoARcPSD|48976196

Python UNIT-1

Python Programming (SRM University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by sujal biranje (biranjesujal@[Link])
lOMoARcPSD|48976196

UNIT-1
INTRODUCTION OF PYTHON: HISTORY AND NEED FOR PYTHON, PYTHON
INSTALLATION AND IDLE, PYTHON SYNTAX, IDENTIFIERS, AND KEYWORDS. DATA
TYPES AND OBJECTS: BASIC DATA TYPES: INTEGRAL AND FLOATING POINT,
NUMERICAL TYPES AND EXPRESSIONS, VARIABLES AND CONSTANTS, COMMENTS
AND DOCUMENTATION STRINGS. BRANCHING AND ITERATION: CONDITIONAL
STATEMENTS (IF, ELIF, ELSE), LOOPING CONSTRUCTS (FOR, WHILE), CONTROL
FLOW STATEMENTS (BREAK, CONTINUE, PASS), ITERATION TECHNIQUES. BASIC
INPUT/OUTPUT: READING FROM AND WRITING TO THE CONSOLE, WORKING
WITH STRINGS AND STRING METHODS. STRUCTURED DATA TYPES: TUPLES AND
TUPLE METHODS, RANGES, LISTS, LIST METHODS, CLONING, AND LIST
COMPREHENSIONS, SETS, SET METHODS, FROZEN SETS, DICTIONARIES,
DICTIONARY METHODS, DEFAULT DICTIONARIES, ORDERED DICTIONARIES, AND
TRAVERSAL.

…………………………………………………………………………………………………………………………

INTRODUCTION OF PYTHON: HISTORY AND NEED FOR PYTHON:

1. Introduction to Python

Python is a high-level, general-purpose, interpreted programming language that


emphasizes readability and simplicity.

 Created by Guido van Rossum in 1989, officially released in 1991.


 Designed to be easy to read (English-like syntax) and easy to learn.
 Used in a wide variety of fields — from web development to data science
to AI.

Python is known for:

 Clean syntax
 Extensive standard library
 Cross-platform compatibility
 Support for multiple programming paradigms (procedural, object-
oriented, functional)

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

2. History of Python

Timeline

 1980s → Guido van Rossum worked at CWI (Centrum Wiskunde &


Informatica) in the Netherlands, contributing to the ABC programming
language.
o He liked ABC’s simplicity but wanted something more powerful and
extensible.
 December 1989 → Guido started developing Python during his Christmas
holidays.
 February 1991 → Python 0.9.0 released (included functions, exception
handling, and core data types: str, list, dict).
 2000 → Python 2.0 released (introduced list comprehensions, garbage
collection).
 2008 → Python 3.0 released (major redesign, not backward-compatible with
Python 2).
 2020 → End of official support for Python 2.
 Present → Python 3.x is widely used and actively developed.

3. Why the Name “Python”?

 Guido van Rossum was a fan of the British comedy series "Monty Python’s
Flying Circus".
 The name “Python” was chosen for being short, unique, and slightly
mysterious — not because of the snake! 🐍

4. Need for Python (Why Python is Popular & Necessary)

Python’s popularity isn’t accidental — it solves real needs:

a) Easy to Learn and Use

 Syntax close to natural language (English)


 Minimal boilerplate code
 Great for beginners and professionals alike

b) Cross-Platform

 Works on Windows, macOS, Linux, and many embedded systems without


code changes.

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

c) Versatile

 Supports web development, machine learning, data analysis, automation,


IoT, game development, and more.

d) Large Standard Library

 Built-in modules for file handling, networking, databases, math, and more.

e) Rich Ecosystem

 Thousands of external packages via PyPI (Python Package Index)


 Popular libraries: NumPy, Pandas, Django, Flask, TensorFlow, OpenCV.

f) Strong Community Support

 Large global community


 Abundant tutorials, forums, and documentation

g) Interpreted Language

 No need to compile — run code directly, making development faster.

h) Integration Friendly

 Can integrate with C, C++, Java, and other languages easily.

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

PYTHON INSTALLATION AND IDLE:

PYTHON SYNTAX, IDENTIFIERS, AND KEYWORDS:

Python Syntax (the “grammar” of code)

Indentation & blocks


 Indentation defines blocks (no braces). Typical style: 4 spaces per level (PEP 8).
 Mixing tabs and spaces for indentation raises TabError in Python 3.

def greet(name):

if name:

print("Hello,", name)

else:

print("Hi!")

Statements & lines


 One statement per line is preferred. Semicolons are optional:

x = 1; y = 2 # legal, but avoid


Long lines: break inside () [] {} (preferred) or with \ (avoid if possible).

total = (

price

+ tax

+ discount

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Comments & docstrings


 Comment: # to end of line.
 Docstring: triple quotes immediately under a module/class/function; becomes __doc__.

def area(r):

"""Return area of a circle with radius r."""

return 3.14159 * r * r

Literals & strings


 Numbers: 123, 1_000_000, 3.14, 0b1010, 0xFF, 1+2j.
 Strings: single/double quotes; multi-line with triple quotes; raw strings r"..."; bytes
b"...".

f-strings for interpolation/formatting:

user, score = "Ada", 98

print(f"{user=} {score:.1f}")
Collections & comprehensions

lst = [1, 2, 3]

tup = (1, 2, 3)

st = {1, 2, 3}

d = {"a": 1, "b": 2}

squares = [x*x for x in range(10) if x % 2 == 0]

Operators & comparisons


 Arithmetic, bitwise, boolean (and, or, not).
 Chained comparisons: 0 < x < 10.
 Identity vs equality: is / is not checks object identity; use == for value equality.

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Assignment & annotations


 Multiple/unpacking:

a, b = 1, 2

a, b = b, a

x, *mid, y = [1, 2, 3, 4, 5]

 Augmented: x += 1.

 Walrus operator := (assign within expressions, Py 3.8+):

if (n := len(items)) > 0:

print(n)
Type hints (optional but recommended):

def add(a: int, b: int) -> int: return a + b

Control flow

if cond: ...

elif other: ...

else: ...

for item in iterable: ...

while condition: ...

try:

...

except ValueError:

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

...

else: # runs if no exception

...

finally: # always runs

...

with open("[Link]") as f: data = [Link]()

Structural pattern matching (Py 3.10+)

match command:
case ("move", x, y):
...
case ("quit",):
...
case _:
...
IMPORTS

import math

import numpy as np

from collections import deque

from package import module as alias

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

IDENTIFIERS (NAMES YOU CREATE)

Rules
 Start with a letter (A–Z / a–z) or underscore _ (Unicode letters allowed).
 Followed by letters, digits, or underscores.
 Cannot be a keyword.
 Case-sensitive: value, Value, and VALUE are different.

Valid: x, _hidden, total_sum, π, data2


Invalid: 2nd, class (keyword), first-name (hyphen not allowed)

Underscore conventions
 _single_leading: non-public by convention (internal use).
 single_trailing_ (e.g., class_): avoid keyword clash.
 __double_leading: name-mangling inside classes (_ClassName__attr).
 __double__ (“dunder”): reserved by convention for special methods (__init__,
__len__).
 _ alone: throwaway variable; in REPL, _ holds last expression result.

PEP 8 naming style (strongly recommended)


 variables/functions/methods: snake_case
 classes/exceptions: PascalCase
 constants: UPPER_SNAKE_CASE
 modules/packages: lower_snake_case

Avoid shadowing builtins


Don’t name a variable list, dict, str, type, id, etc. Use lst, mapping, text, etc.

Keywords (reserved words)

Keywords are part of the language syntax—you cannot use them as identifiers.

Python 3.10+ (incl. 3.12/3.13) keyword set:

False, None, True, and, as, assert, async, await, break, case, class,
continue, def, del, elif, else, except, finally, for, from, global, if,

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

import, in, is, lambda, match, nonlocal, not, or, pass, raise, return, try,
while, with, yield

DATA TYPES AND OBJECTS: BASIC DATA TYPES: INTEGRAL AND FLOATING POINT,
NUMERICAL TYPES AND EXPRESSIONS:

Since Python is dynamically typed, the data type of a variable is determined at


runtime based on the assigned value.

In general, the data types are used to define the type of a variable. It represents the
type of data we are going to store in a variable and determines what operations can
be done on it.

Types of Data Types in Python

Python supports the following built-in data types −

 Numeric Data Types


o int
o flot
o complex
 String Data Types
 Sequence Data Types
o list
o tuple
o range
 Binary Data Types
o bytes
o bytearray
o memoryview
 Dictionary Data Type
 Set Data Type
o set
o frozenset
 Boolean Data Type
 None Type

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

1. Python Numeric Data Types


var1 = 1 # int data type
var2 = True # bool data type
var3 = 10.023 # float data type
var4 = 10+3j # complex data type

To know type of data:


 >>> type(5+6j)
 <class 'complex'>
Example:
# integer variable.
a=100

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

print("The type of variable having value", a, " is ", type(a))


# float variable.
c=20.345
print("The type of variable having value", c, " is ", type(c))
# complex variable.
d=10+3j print("The type of variable having value", d, " is ",
type(d))

2. Python String Data Type


Python string is a sequence of one or more Unicode characters, enclosed in
single, double or triple quotation marks (also called inverted commas). Python
strings are immutable which means when you perform an operation on strings,
you always produce a new string object of the same type, rather than mutating
an existing string.

>>> 'TutorialsPoint'
'TutorialsPoint'
>>> "TutorialsPoint"
'TutorialsPoint'
>>> '''TutorialsPoint'''
'TutorialsPoint'
A string in Python is an object of str class. It can be verified
with type() function.

>>> type("Welcome To TutorialsPoint")


<class 'str'>

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Example of String Data Type

str = 'Hello World!' print (str) # Prints complete string


print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 5th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST") # Prints concatenated string
OUTPUT
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

VARIABLES AND CONSTANTS:

Python, being a dynamically typed, interpreted, and high-level language, handles variables
and constants in a very flexible way compared to languages like C or Java.

1. Variables in Python

Definition:

A variable in Python is simply a name that refers (or points) to a value stored in
memory.
Unlike many other languages, Python does not require declaring the type of a
variable explicitly. The type is inferred automatically at runtime based on the
value assigned.

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

How to Create Variables in Python:

 Use the assignment operator = to assign values.


 Example:
 x = 10 # integer
 name = "John" # string
pi = 3.14

Characteristics of Variables in Python:

1. Dynamic Typing:
The same variable can hold values of different types during execution.
2. x = 10 # int
3. x = "Hello" # string
4. No Explicit Declaration:
You don’t need to specify type; Python figures it out.
5. Case-Sensitive:
Age and age are different variables.
6. Memory Management:
Python automatically allocates and manages memory for variables.

Rules for Naming Variables in Python:

✅ Can include letters (A–Z, a–z), digits (0–9), and underscore (_).
✅ Must not start with a digit.
✅ Cannot use Python keywords (e.g., class, def, import).
✅ Case-sensitive.

Valid examples:

count = 10
student_name = "Alice"
_temp = 99

Invalid examples:

2value = 100 # cannot start with number


my-name = "Bob" # hyphen not allowed

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

class = 5 # 'class' is a keyword


int=5

Types of Variables in Python:

Global Variables: Declared outside functions, accessible throughout the


program.

x = 50 # global variable

def show():
print(x)

show()
print(x)

Local Variables: Declared inside a function, accessible only within that


function.

def func():
y = 20 # local variable
print(y)

func()

Nonlocal Variables (special case): Used inside nested functions to access


variables from the outer (but not global) scope.

def outer():
x = "outer"
def inner():
nonlocal x
x = "modified in inner"
print(x)
inner()
print(x)

outer()

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Example of Using Variables:

age = 21
name = "Priya"
height = 5.6

print("Name:", name)
print("Age:", age)
print("Height:", height)

2. Constants in Python

Definition:

A constant in Python is a variable whose value should not be changed during


program execution.

🐍 BUT: Unlike C, C++, or Java, Python does not have built-in constant
keywords. Instead, by convention, constants are written in uppercase letters with
underscores separating words.

Declaring Constants:

PI = 3.14159
GRAVITY = 9.8
MAX_USERS = 100

These are constants by convention. Python will not stop you from reassigning
them, but developers treat them as "read-only".

Using const (Optional via External Library):

Python doesn’t enforce constants natively.


However, there are workarounds:

 Use external libraries (e.g., const module).


 Or create a class for constants.

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Example using a class for constants:

class Constants:
PI = 3.14159
GRAVITY = 9.8

print([Link])

Example of Constant Usage:

PI = 3.14159
radius = 7

area = PI * radius * radius


print("Area of Circle:", area)

If someone reassigns PI = 4.5, it would still work, but this goes against coding
best practices.

3. Difference Between Variables and Constants in Python

Aspect Variables Constants


Name referring to data that Name referring to fixed data that
Definition
can change should not change
Value can change during
Mutability Value remains fixed (by convention)
execution
Declaration Normal assignment (x = 10) Written in uppercase (PI = 3.14)
Only a naming convention (not
Enforcement Fully enforced by Python
enforced)
Age, scores, user inputs, Mathematical constants, fixed
Use Case
counters configuration values

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

4. Importance of Variables & Constants in Python

 Variables provide flexibility to store changing data (user inputs, counters,


calculations).
 Constants ensure fixed values remain unchanged (mathematical constants,
configuration limits).
 Together, they make programs clear, maintainable, and reliable.

COMMENTS AND DOCUMENTATION STRINGS:

COMMENTS IN PYTHON

Comments are non-executable statements in Python used to explain code,


improve readability, and help programmers understand logic.

They are ignored by the Python interpreter.

✅ Types of Comments in Python:

1. Single-line Comment
o Starts with #
o Used for short explanations.
2. # This is a single-line comment
3. x = 10 # variable storing integer
4. Multi-line Comment
o Python does not have a special syntax for multi-line comments.

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

o We use multiple single-line comments OR triple quotes (''' or """)


(though triple quotes are technically string literals, they can be used as
block comments if not assigned to a variable).
5. # This is line 1 of the comment
6. # This is line 2 of the comment
7. # This is line 3 of the comment
8.
9. '''
10. This is a multi-line comment
11. written using triple quotes.
12. '''

DOCUMENTATION STRINGS (DOCSTRINGS)

A docstring is a string literal written just below the definition of a module, class,
function, or method.
It is used to document what the code does and can be accessed using the __doc__
attribute.

✅ Features of Docstrings:

 Written inside triple quotes (""" or ''').


 Can span multiple lines.
 Helps in code documentation and auto-generated help messages.

🔹 Example of Docstrings

Function Docstring

def add(a, b):


"""Return the sum of two numbers a and b."""
return a + b

print(add.__doc__)

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Output:

Return the sum of two numbers a and b.

Multi-line Function Docstring

def divide(a, b):


"""
Divide two numbers.

Parameters:
a (int or float): numerator
b (int or float): denominator (must not be zero)

Returns:
float: result of division
"""
return a / b

print(divide.__doc__)

Class Docstring

class Person:
"""This class represents a person with name and age."""

def __init__(self, name, age):


"""Initialize name and age of the person."""
[Link] = name
[Link] = age

def greet(self):
"""Print a greeting message."""
print(f"Hello, my name is {[Link]}.")

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Module Docstring

At the top of a Python file, you can write a module-level docstring:

"""
This module demonstrates arithmetic operations.

Functions:
- add(a, b): returns sum
- subtract(a, b): returns difference
- multiply(a, b): returns product
- divide(a, b): returns quotient
"""

BRANCHING AND ITERATION:

1. Branching in Python

Branching means decision-making in a program, where the program chooses


different paths based on conditions.

Conditional Statements

Python provides if, elif, and else.

Syntax
if condition1:
# block executed if condition1 is True
elif condition2:
# block executed if condition2 is True
else:
# block executed if none of the above conditions are True
Example
age = 18

if age < 13:

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")

Output:

Teenager

🐍 if → checks a condition
🐍 elif → checks additional conditions
🐍 else → default case (runs if all conditions are False)

2. Iteration in Python

Iteration means repeating a block of code multiple times, usually using loops.

Types of Loops

1. for loop – used when the number of iterations is known or we are looping
through a sequence.
2. while loop – used when the number of iterations is not fixed, but depends on
a condition.

2.1. for Loop

Syntax
for variable in sequence:
# code block
Example
for i in range(5):
print("Iteration:", i)

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Output:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

🐍 range(5) generates numbers from 0 to 4.

Iterating through a list


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

2.2. while Loop

Syntax
while condition:
# code block
Example
count = 1
while count <= 5:
print("Count:", count)
count += 1

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

2.3. Loop Control Statements

 break → exits the loop immediately.


 continue → skips the current iteration and moves to the next.

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

 pass → does nothing (placeholder).

Example
for i in range(1, 6):
if i == 3:
continue
if i == 5:
break
print(i)

Output:

1
2
4

CONTROL FLOW STATEMENTS (BREAK, CONTINUE, PASS):

In Python, control flow statements (break, continue, and pass) are used to control
the execution of loops and conditional blocks.

🔹 1. break Statement

 Purpose: Terminates the loop immediately when a certain condition is met.


 After break, the program continues with the first statement after the loop.

Example:

for num in range(1, 10):


if num == 5:
break # loop stops when num = 5
print(num)

Output:

1
2
3
4

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

🔹 2. continue Statement

 Purpose: Skips the current iteration of the loop and continues with the next
iteration.
 It does not exit the loop, only skips the remaining code for the current cycle.

Example:

for num in range(1, 10):


if num == 5:
continue # skips printing 5
print(num)

Output:

1
2
3
4
6
7
8
9

🔹 3. pass Statement

 Purpose: A null statement in Python.


 It does nothing but acts as a placeholder to avoid syntax errors.
 Useful when you want to leave code empty temporarily.

Example:

for num in range(1, 6):


if num == 3:
pass # does nothing here
print(num)

Output:

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

1
2
3
4
5

✅ Summary Table

Statement Function Effect on Loop


break Exits the loop Loop ends immediately
continue Skips current Goes to next iteration
iteration
pass Does nothing Just a placeholder

BASIC INPUT/OUTPUT: READING FROM AND WRITING TO THE CONSOLE:

Python provides simple and intuitive ways to handle input and output operations.
Here's a quick guide:

1. Reading Input from the Console

To take input from the user, Python uses the input() function. It reads input as a
string by default.
Copy code# Example: Taking user input
name = input("Enter your name: ")
print("Hello, " + name + "!")

 Key Points:
o The input() function displays the prompt (if provided) and waits for
the user to type something.
o The input is always returned as a string. Use type conversion if
needed.
Copy code# Example: Taking numerical input
age = int(input("Enter your age: "))
print("You are", age, "years old.")

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

2. Writing Output to the Console

Python uses the print() function to display output.


Copy code# Example: Printing output
print("Welcome to Python programming!")

 Formatting Output: You can format output using f-strings (Python


3.6+), [Link](), or concatenation.
Copy code# Using f-strings
name = "Alice"
print(f"Hello, {name}!")

# Using [Link]()
print("Hello, {}!".format(name))

# Concatenation
print("Hello, " + name + "!")

3. Advanced Input/Output

 Reading Multiple Inputs: Use split() to handle multiple inputs in one line.
Copy code# Example: Reading multiple inputs
x, y = input("Enter two numbers separated by space: ").split()
print(f"First number: {x}, Second number: {y}")

 Customizing Output: Use the sep and end parameters in print().


Copy code# Example: Customizing print
print("Python", "is", "fun", sep="-", end="!\n")

# Example: Taking user input

name = input("Enter your name: ")

print("Hello, " + name + "!")

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

WORKING WITH STRINGS AND STRING METHODS:

1. What is a String?

 A string in Python is a sequence of characters enclosed in single quotes


(' '), double quotes (" "), or triple quotes (''' ''' / """ """).
 Strings are immutable, meaning once created, they cannot be changed.

Examples:

str1 = 'Hello'
str2 = "World"
str3 = '''Python Programming'''

🔹 2. String Creation

s1 = "Python"
s2 = 'AI'
s3 = """This is
a multiline string."""

🔹 3. Accessing Strings

Strings are like arrays of characters (indexed).

text = "Python"
print(text[0]) # P (first character)
print(text[-1]) # n (last character)
print(text[0:4]) # Pyth (slicing)

🔹 4. String Operations

 Concatenation (+)

a = "Hello"
b = "World"
print(a + " " + b) # Hello World

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

 Repetition (*)

print("Hi! " * 3) # Hi! Hi! Hi!

 Membership (in, not in)

msg = "Python is fun"


print("fun" in msg) # True
print("Java" not in msg) # True

🔹 5. Common String Methods

Python provides many built-in methods to manipulate strings.

Method Description Example


Converts string to
lower() "PYTHON".lower() → 'python'
lowercase
Converts string to
upper() "python".upper() → 'PYTHON'
uppercase
Capitalizes first letter of
title() "hello world".title() → 'Hello World'
each word
capitalize() Capitalizes only first letter "python".capitalize() → 'Python'
Removes whitespace from
strip() " hello ".strip() → 'hello'
both ends
lstrip() / Removes left/right
" hello".lstrip() → 'hello'
rstrip() whitespace
replace(old, "hello world".replace("world",
Replaces substring
new) "Python") → 'hello Python'
split() Splits string into list "a,b,c".split(",") → ['a','b','c']
join() Joins list into string "-".join(['a','b','c']) → 'a-b-c'
Returns index of substring
find() "Python".find("th") → 2
(−1 if not found)
Counts occurrences of
count() "banana".count("a") → 3
substring
Checks if string starts with
startswith() "Python".startswith("Py") → True
value

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Method Description Example


Checks if string ends with
endswith() "Python".endswith("on") → True
value
Checks if all characters are
isdigit() "123".isdigit() → True
digits
Checks if all characters are
isalpha() "Python".isalpha() → True
alphabets
Checks if string is
isalnum() "Python3".isalnum() → True
alphanumeric

🔹 6. String Formatting

 Using f-strings (Recommended in Python 3.6+)

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

 Using .format()

print("My name is {} and I am {} years old.".format("Alice", 25))

🔹 7. Iterating Over a String

text = "Python"
for ch in text:
print(ch, end=" ")
# Output: P y t h o n

🔹 8. String Immutability

Strings cannot be changed directly.

s = "Python"
# s[0] = "J" ❌Error
s = "J" + s[1:] # ✅Correct
print(s)

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

# Jython
STRUCTURED DATA TYPES: TUPLES AND TUPLE METHODS RANGES

1. What is a Tuple?

 A tuple is a collection data type in Python, used to store multiple items in a


single variable.
 It is ordered, immutable (cannot be changed after creation), and allows
duplicates.
 Tuples are written with round brackets ( ).

Example:

# Creating tuples
t1 = (10, 20, 30)
t2 = ("apple", "banana", "cherry")
t3 = (1, 2, 3, 2, 1)
print(t1)
print(t2)
print(t3)

2. Characteristics of Tuples

 Ordered: Elements have a fixed position.


 Immutable: Cannot change, add, or remove elements.
 Heterogeneous: Can contain elements of different data types (e.g., int,
string, float).
 Allow duplicates.

3. Accessing Elements

Like lists, you can access tuple elements using indexing and slicing.

t = (100, 200, 300, 400, 500)

print(t[0]) # First element → 100


print(t[-1]) # Last element → 500
print(t[1:4]) # Slicing → (200, 300, 400)

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

4. Tuple Methods

Tuples have limited methods because they are immutable.


The two main methods are:

(a) count()

Returns the number of times a specified value occurs.

t = (1, 2, 3, 2, 4, 2)
print([Link](2)) # Output: 3

(b) index()

Returns the index of the first occurrence of a specified value.

t = ("apple", "banana", "cherry", "apple")


print([Link]("apple")) # Output: 0

5. Tuple Operations

Even though tuples are immutable, you can still perform some operations:

Concatenation

t1 = (1, 2, 3)
t2 = (4, 5, 6)
print(t1 + t2) # (1, 2, 3, 4, 5, 6)

Repetition

t = (7, 8)
print(t * 3) # (7, 8, 7, 8, 7, 8)

Membership Test

t = (1, 2, 3, 4)
print(3 in t) # True
print(5 not in t) # True

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

Length

t = ("a", "b", "c")


print(len(t)) # 3

6. Conversion between Tuples and Other Data Types

You can convert tuples to other data structures:

# Tuple to List
t = (1, 2, 3)
lst = list(t)
print(lst)

# List to Tuple
l = [4, 5, 6]
t2 = tuple(l)
print(t2)

7. Nested Tuples

Tuples can contain other tuples (multi-dimensional).

t = ((1, 2), (3, 4), (5, 6))


print(t[1]) # (3, 4)
print(t[1][0]) # 3

LISTS, LIST METHODS, LONING, AND LIST COMPREHENSIONS:

1. Lists in Python

A list is a collection of ordered, mutable (changeable) items in Python.


It can store elements of different data types (integers, strings, floats, objects).

Creating a List

# Examples of lists
numbers = [1, 2, 3, 4, 5] # list of integers

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

mixed = [10, "hello", 3.14, True] # list with multiple data types
nested = [[1, 2], [3, 4]] # nested list (list inside a list)
empty_list = [] # empty list

Accessing Elements

fruits = ["apple", "banana", "cherry", "mango"]

print(fruits[0]) # apple (first element)


print(fruits[-1]) # mango (last element)
print(fruits[1:3]) # ['banana', 'cherry'] (slicing)

2. List Methods

Python provides many built-in methods to work with lists:

Method Description
append(x) Adds x to the end of the list.
Adds multiple elements from another iterable (list/tuple) to the
extend(iterable)
list.
insert(i, x) Inserts x at index i.
remove(x) Removes first occurrence of x.
Removes and returns element at index i. Default removes last
pop([i])
element.
clear() Removes all elements from the list.
index(x) Returns first index of x.
count(x) Returns number of occurrences of x.
sort() Sorts the list in ascending order (modifies original list).
reverse() Reverses the list in place.
copy() Returns a shallow copy of the list.

Examples

nums = [10, 5, 8, 1]

[Link](20) # [10, 5, 8, 1, 20]


[Link](2, 15) # [10, 5, 15, 8, 1, 20]

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

[Link](5) # [10, 15, 8, 1, 20]


[Link]() # removes last → [10, 15, 8, 1]
[Link]() # [1, 8, 10, 15]
[Link]() # [15, 10, 8, 1]

3. Cloning Lists

Cloning means creating a copy of the list so changes to one do not affect the other.

Different Ways to Clone

list1 = [1, 2, 3]

# Method 1: Using slicing


list2 = list1[:]

# Method 2: Using copy()


list3 = [Link]()

# Method 3: Using list() constructor


list4 = list(list1)

# Method 4: Using copy module (deep copy for nested lists)


import copy
list5 = [Link](list1)

[Link](4)
print(list1) # [1, 2, 3, 4]
print(list2) # [1, 2, 3] (remains unaffected)

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

4. List Comprehensions

List comprehension provides a concise way to create lists using a single line of
code.

Syntax

[expression for item in iterable if condition]

Examples

# Create a list of squares


squares = [x**2 for x in range(1, 6)]
# [1, 4, 9, 16, 25]

# Get even numbers from a list


numbers = [1, 2, 3, 4, 5, 6]
evens = [x for x in numbers if x % 2 == 0]
# [2, 4, 6]

# Create a list of uppercase words


words = ["apple", "banana", "cherry"]
upper_words = [[Link]() for word in words]
# ['APPLE', 'BANANA', 'CHERRY']

# Nested comprehension (flatten a 2D list)


matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]

Downloaded by sujal biranje (biranjesujal@[Link])


lOMoARcPSD|48976196

SETS, SET METHODS, FROZEN SETS:

DICTIONARIES, DICTIONARY METHODS, DEFAULT DICTIONARIES, ORDERED


DICTIONARIES, AND TRAVERSAL.

Downloaded by sujal biranje (biranjesujal@[Link])

You might also like