0% found this document useful (0 votes)
17 views15 pages

Plus One Notes

The document covers fundamental programming concepts in Python, including conditional statements, looping constructs, and built-in functions for strings, lists, tuples, and dictionaries. It explains the syntax and usage of various control structures, data types, and methods, providing examples for clarity. Additionally, it discusses modules, their types, and how to import and use them in Python programs.

Uploaded by

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

Plus One Notes

The document covers fundamental programming concepts in Python, including conditional statements, looping constructs, and built-in functions for strings, lists, tuples, and dictionaries. It explains the syntax and usage of various control structures, data types, and methods, providing examples for clarity. Additionally, it discusses modules, their types, and how to import and use them in Python programs.

Uploaded by

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

CHAPTER 5:

CONDITIONAL STATEMENTS AND LOOPING


CONSTRUCTS
============================
1. CONDITIONAL STATEMENTS
A. if Statement

Executes a block only when the condition is True.

if condition:
statements

B. if–else Statement

Executes one block if the condition is True, otherwise another block.

if condition:
statements
else:
statements

C. if–elif–else Statement

Used when multiple conditions need to be checked.

if condition1:
...
elif condition2:
...
else:
...

D. Nested if

An if statement inside another if.

2. LOOPING CONSTRUCTS
A. for Loop

Used to iterate over a sequence (string, list, tuple, range).

for variable in sequence:


statements
B. while Loop

Executes repeatedly as long as the condition remains True.

while condition:
statements

3. LOOP CONTROL STATEMENTS


1. break

Exits the loop immediately.

2. continue

Skips the current iteration and moves to next iteration.

3. pass

Does nothing (placeholder).

4. else with loops

Executed when loop finishes normally without a break.

4. BUILT-IN FUNCTIONS USED IN LOOPS


range()

Generates a sequence of numbers.

Syntax Meaning
range(stop) 0 to stop-1
range(start, stop) start to stop-1
range(start, stop, step) step increments

Examples:
range(5) → 0 1 2 3 4
range(2, 7) → 2 3 4 5 6
range(1, 10, 2) → 1 3 5 7 9

len()

Returns number of items.


len("Hello") → 5
len([1,2,3]) → 3

type()
Returns datatype.
type(10) → int

id()

Returns memory address of an object.

============================
CHAPTER 6: STRINGS IN PYTHON
============================

1. What is a String?
A sequence of characters enclosed in quotes.

Strings are immutable.


This means we cannot change characters directly.

2. String Indexing
 Positive indexing → starts from 0
 Negative indexing → starts from -1

Example:
s = "PYTHON"
s[0] → 'P'
s[-1] → 'N'

3. String Slicing
Used to extract a substring.

s[start:end:step]

Examples:

 s[0:3] → 'PYT'
 s[:4] → 'PYTH'
 s[::-1] → reverse

4. STRING BUILT-IN FUNCTIONS / METHODS


A. Case Conversion Methods
1. upper()

Converts to uppercase.
"hello".upper() → "HELLO"

2. lower()

Converts to lowercase.

3. title()

Capitalizes first letter of each word.

4. capitalize()

Makes first character uppercase.

B. Test Methods
1. isdigit()

Returns True if all characters are digits.

2. isalpha()

True if all are alphabets.

3. isalnum()

True if alphabets or digits (no special characters).

4. islower() / isupper()

Check case of string.

5. isspace()

True if string contains only spaces.

C. Searching Methods
1. find(sub)

Returns index of first occurrence or -1 if not found.

2. rfind(sub)

Searches from right side.


3. index(sub)

Same as find() but gives error if substring not found.

D. Modification Methods
1. replace(old, new)

Replaces text.

2. strip()

Removes spaces from both ends.


" hello ".strip() → "hello"

3. lstrip() / rstrip()

Remove left / right spaces.

4. split()

Splits string into a list.


"a,b,c".split(",") → ['a','b','c']

5. join()

Joins list elements into a string.


"-".join(['1','2','3']) → "1-2-3"

E. Other Useful Built-in Functions


len()

Total characters.

max() / min()

Finds highest / lowest ASCII value character.

ord()

ASCII value of character.

chr()

Character of given ASCII value.

============================
CHAPTER 7: LISTS IN PYTHON
============================

1. What is a List?
 Ordered
 Mutable
 Heterogeneous
 Allows duplicates

Example:
a = [10, "hello", 3.5]

2. List Indexing & Slicing


Same as strings.

lst[0] → first element


lst[-1] → last element
lst[1:4] → slice

3. LIST BUILT-IN METHODS

A. Adding Elements
1. append(x)

Adds element at end.


[Link](10)

2. insert(pos, x)

Inserts at a specific index.

3. extend(list2)

Adds elements of another list.


[1,2].extend([3,4]) → [1,2,3,4]

B. Removing Elements
1. remove(x)

Removes first occurrence of x.


2. pop()

Removes last element.

3. pop(index)

Removes element at given index.

4. clear()

Removes all elements.

C. Other Useful List Methods


1. sort()

Sorts list in ascending order.

2. sorted(list)

Returns a new sorted list (does not modify original).

3. reverse()

Reverses all elements.

4. count(x)

Counts occurrences.

5. index(x)

Returns index of first occurrence.

4. Built-in Functions for Lists


1. len(list)

Number of items.

2. sum(list)

Sum of numeric elements.

3. max(list) / min(list)

Largest / smallest element.

4. list()
Converts to list.

5. range()

Often used to generate lists.

5. List Operations
 Concatenation: +
 Repetition: *
 Membership: in, not in
 Length: len(list)

6. Traversing Lists
Using for loop:
for item in lst:
print(item)

Using index:
for i in range(len(lst)):
print(lst[i])

Example programs
1. Check if a number is positive or negative
n = int(input("Enter number: "))
if n > 0:
print("Positive")
else:
print("Negative")

2. Check whether number is even or odd


n = int(input("Enter number: "))
if n % 2 == 0:
print("Even")
else:
print("Odd")

3. Largest of two numbers


a = int(input("Enter first: "))
b = int(input("Enter second: "))
if a > b:
print("A is larger")
else:
print("B is larger")

4. Grade based on marks


m = int(input("Enter marks: "))
if m >= 90:
print("A Grade")
elif m >= 75:
print("B Grade")
elif m >= 60:
print("C Grade")
else:
print("Needs Improvement")

5. Print numbers 1 to 5 (for loop)


for i in range(1, 6):
print(i)

6. Print even numbers from 1 to 20


for i in range(2, 21, 2):
print(i)

7. Print each character in a string


for ch in "HELLO":
print(ch)

8. Sum of first 10 numbers


s = 0
for i in range(1, 11):
s += i
print("Sum =", s)

9. While loop: keep asking number until user enters 0


n = 1
while n != 0:
n = int(input("Enter number (0 to stop): "))

10. Reverse a string


s = input("Enter string: ")
print("Reverse:", s[::-1])

11. Convert to uppercase and lowercase


s = input("Enter: ")
print([Link]())
print([Link]())
12. Print each element in a list
a = [10, 20, 30]
for i in a:
print(i)

13. Replace the 3rd element


a = [1, 2, 9, 4]
a[2] = 99
print(a)

14. Reverse a list


a = [1, 2, 3, 4]
print(a[::-1])

15. Find the sum of a list


a = [5, 10, 15, 20]
s = 0
for i in a:
s += i
print("Sum =", s)

CHAPTER 8
TUPLES AND DICTIONARY

What is a Tuple?

A tuple is an ordered collection of elements enclosed in parentheses ( ).


Tuples are immutable, which means their values cannot be changed after creation.

Example

t = (10, 20, 30)

Features of Tuples

 Ordered (indexing allowed)


 Immutable (no modification)
 Can store different data types
 Faster than lists
 Allows duplicate values

Creating Tuples
t1 = (1, 2, 3)
t2 = ("A", "B", "C")
t3 = (10,) # Single element tuple (comma is required)
t4 = () # Empty tuple
Accessing Tuple Elements

Indexing starts from 0.

t = (10, 20, 30)


print(t[0]) # Output: 10
print(t[-1]) # Output: 30

Tuple Slicing
t = (1, 2, 3, 4, 5)
print(t[1:4]) # Output: (2, 3, 4)

Tuple Operations

1. Concatenation
t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # (1, 2, 3, 4)
2. Repetition
t = (1, 2)
print(t * 3) # (1, 2, 1, 2, 1, 2)
3. Membership
t = (10, 20, 30)
print(20 in t) # True

Tuple Functions

Function Description

len(t) Returns number of elements

max(t) Largest element

min(t) Smallest element

sum(t) Sum of elements

[Link](x) Count occurrences

[Link](x) Position of element

Tuple Packing and Unpacking


t = (10, 20, 30) # Packing
a, b, c = t # Unpacking
print(a, b, c)

Why Tuples?

 Used when data should not change


 Used in functions to return multiple values
 Faster than lists

DICTIONARY
What is a Dictionary?

A dictionary is a collection of key–value pairs enclosed in curly braces { }.

Example

student = {"name": "Rahul", "marks": 85}

Features of Dictionary

 Unordered (but ordered in Python 3.7+)


 Mutable (values can be changed)
 Keys must be unique
 Keys must be immutable (string, number, tuple)

Creating Dictionary
d = {"A": 10, "B": 20}
empty = {}

Accessing Values
d = {"name": "Riya", "age": 16}
print(d["name"]) # Riya

Using get() method:

print([Link]("age"))

Adding / Updating Elements


d = {"A": 10}
d["B"] = 20 # Add
d["A"] = 15 # Update

Deleting Elements
del d["A"] # Delete specific key
[Link]("B") # Remove and return value
[Link]() # Remove all items

Dictionary Functions & Methods


Method Description

len(d) Number of items

[Link]() Returns all keys

[Link]() Returns all values

[Link]() Returns key-value pairs

[Link](d2) Adds items from another dictionary

Example:

d = {"A":10, "B":20}
print([Link]())
print([Link]())
print([Link]())

Traversing Dictionary
d = {"A":10, "B":20}
for key in d:
print(key, d[key])

Nested Dictionary
students = {
"s1": {"name": "Ravi", "marks": 80},
"s2": {"name": "Anu", "marks": 90}
}

Applications

 Student records
 Database-like storage
 Frequency counting

PYTHON MODULES
What is a Module?

A module is a file containing Python code (functions, variables, classes) that can be reused in
another program.

Example: [Link], [Link]

Types of Modules

1. Built-in Modules
2. User-defined Modules

Importing Modules

Method 1: Import entire module


import math
print([Link](25))

Method 2: Import specific function


from math import sqrt
print(sqrt(16))

Method 3: Import with alias


import math as m
print([Link](36))

Common Built-in Modules

1. math Module

Function Description

sqrt(x) Square root

pow(x,y) x^y

ceil(x) Next integer

floor(x) Previous integer

Example:

import math
print([Link](4.2))

2. random Module

Used to generate random numbers.

Function Description

random() Number between 0 and 1

randint(a,b) Random integer

choice(list) Random element

shuffle(list) Shuffle list


Example:

import random
print([Link](1,10))

Creating User-defined Module

Step 1: Create a file ([Link])


def add(a,b):
return a+b

Step 2: Use in another program


import mymodule
print([Link](2,3))

Module Search Path

Python searches modules in:

 Current directory
 Standard library
 Installed packages

Advantages of Modules

 Code reuse
 Organized programs
 Easy debugging
 Saves time

You might also like