0% found this document useful (0 votes)
39 views21 pages

Python Basics: Strings, Lists, Tuples, and More

The document provides a comprehensive overview of various Python programming concepts, including string manipulation, list operations, tuple handling, dictionary usage, set operations, and search algorithms. It also covers lambda functions, mathematical functions, random number generation, and function definitions with positional and keyword arguments. Additionally, it includes practical examples and exercises for each concept, making it a useful resource for learning Python.

Uploaded by

Anil Bhosale
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)
39 views21 pages

Python Basics: Strings, Lists, Tuples, and More

The document provides a comprehensive overview of various Python programming concepts, including string manipulation, list operations, tuple handling, dictionary usage, set operations, and search algorithms. It also covers lambda functions, mathematical functions, random number generation, and function definitions with positional and keyword arguments. Additionally, it includes practical examples and exercises for each concept, making it a useful resource for learning Python.

Uploaded by

Anil Bhosale
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

# 1.

Create a string and print it

s = "Hello, Python!"

print("Original string:", s)

# 2. Indexing and slicing

print("Character at index 1:", s[1]) # indexing

print("Substring from index 0 to 5:", s[0:5]) # slicing

print("Last character:", s[-1]) # negative indexing

# 3. Concatenate two strings

s2 = " Welcome!"

concatenated = s + s2

print("Concatenated string:", concatenated)

# 4. Repeat a string 4 times

repeated = s * 4

print("Repeated string:", repeated)

# 5. Check if a substring exists in the string

substring = "Python"

if substring in s:

print(f"'{substring}' exists in the string.")

else:

print(f"'{substring}' does NOT exist in the string.")

# 1. Create a list of 10 integers and print it

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

print("Original List:", list1)


# 2. Indexing and slicing

print("Element at index 3:", list1[3]) # Single element

print("Sliced list (index 2 to 6):", list1[2:7]) # Sublist

# 3. Concatenate two lists

list2 = [110, 120, 130]

concatenated_list = list1 + list2

print("Concatenated List:", concatenated_list)

# 4. Repeat a list 4 times

repeated_list = list2 * 4

print("Repeated List (list2 * 4):", repeated_list)

# 5. Add new elements to the list

[Link](200) # Add a single element

[Link]([300, 400]) # Add multiple elements

[Link](2, 15) # Insert element at index 2

print("List after adding elements:", list1)

# 1. Create a tuple of 10 integers and print it

tuple1 = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)

print("Original Tuple:", tuple1)

# 2. Indexing and slicing

print("Element at index 3:", tuple1[3])

print("Slice from index 2 to 6:", tuple1[2:7])

# 3. Concatenate two tuples

tuple2 = (110, 120, 130)


concat_tuple = tuple1 + tuple2

print("Concatenated Tuple:", concat_tuple)

# 4. Repeat a tuple 4 times

repeated_tuple = tuple2 * 4

print("Tuple repeated 4 times:", repeated_tuple)

# 5. Find the index of an element in the tuple

element = 70

index_of_element = [Link](element)

print(f"Index of element {element}:", index_of_element)

# 6. Count the occurrences of an element

count_element = 30

count_of_element = [Link](count_element)

print(f"Count of element {count_element}:", count_of_element)

# 1. Create a dictionary with key-value pairs and print it

student = {

"name": "John",

"age": 20,

"course": "Computer Science",

"grade": "A"

print("Original Dictionary:", student)

# 2. Add a new key-value pair to the dictionary

student["city"] = "New York"

print("\nAfter Adding New Key-Value Pair:", student)


# 3. Remove a key-value pair using del

del student["grade"]

print("\nAfter Removing 'grade' Using del:", student)

# 3 (continued). Remove a key-value pair using pop()

removed_value = [Link]("age")

print("\nAfter Removing 'age' Using pop():", student)

print("Removed Value:", removed_value)

# 4. Access the value of a key in the dictionary

print("\nAccessing Value of 'course':", student["course"])

# 5. Check if a key exists in the dictionary

key_to_check = "name"

if key_to_check in student:

print(f"\nKey '{key_to_check}' exists in the dictionary.")

else:

print(f"\nKey '{key_to_check}' does not exist in the dictionary.")

# -------------------- SET OPERATIONS --------------------

print("----- SET OPERATIONS -----")

# 1. Create a set and print it

set1 = {1, 2, 3, 4, 5}

print("Original Set:", set1)

# 2. Add and remove elements

[Link](6)
print("After add(6):", set1)

[Link](3) # raises error if element not present

print("After remove(3):", set1)

[Link](10) # does not raise error if element not present

print("After discard(10):", set1)

# 3. Set union, intersection, difference, symmetric difference

set2 = {4, 5, 6, 7, 8}

print("Set2:", set2)

print("Union:", set1 | set2) # or [Link](set2)

print("Intersection:", set1 & set2) # or [Link](set2)

print("Difference (set1 - set2):", set1 - set2) # elements in set1 not in set2

print("Symmetric Difference:", set1 ^ set2) # elements in set1 or set2 but not both

# 4. Subset and superset

print("set1 is subset of set2?", set1 <= set2)

print("set1 is superset of set2?", set1 >= set2)

# 5. Check if element is present

element = 4

print(f"Is {element} in set1?", element in set1)

# -------------------- LINEAR SEARCH --------------------

print("\n----- LINEAR SEARCH -----")

def linear_search(arr, key):

for i in range(len(arr)):
if arr[i] == key:

return i

return -1

arr = [10, 20, 30, 40, 50]

key = 30

index = linear_search(arr, key)

if index != -1:

print(f"Element {key} found at index {index}")

else:

print(f"Element {key} not found")

# -------------------- BINARY SEARCH (Iterative) --------------------

print("\n----- BINARY SEARCH -----")

def binary_search(arr, key):

low = 0

high = len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == key:

return mid

elif arr[mid] < key:

low = mid + 1

else:

high = mid - 1

return -1

sorted_arr = [10, 20, 30, 40, 50] # must be sorted

key = 40
index = binary_search(sorted_arr, key)

if index != -1:

print(f"Element {key} found at index {index} (Binary Search)")

else:

print(f"Element {key} not found (Binary Search)")

# 1. Create a list of the first 20 even numbers

even_numbers = [i*2 for i in range(1, 21)]

print("First 20 even numbers:", even_numbers)

# 2. Create a list of numbers from 1 to 5 and find their squares

numbers = [1, 2, 3, 4, 5]

squares = [x**2 for x in numbers]

print("Squares of numbers 1 to 5:", squares)

# 3. Create a list of the first 5 odd numbers

odd_numbers = [2*i - 1 for i in range(1, 6)]

print("First 5 odd numbers:", odd_numbers)

# 4. Create a list of numbers from 1 to 5 and multiply each number by 3

multiplied_by_3 = [x*3 for x in numbers]

print("Numbers 1 to 5 multiplied by 3:", multiplied_by_3)

# 5. Create a list to double each element in a given list

original_list = [10, 20, 30, 40]

doubled_list = [x*2 for x in original_list]

print("Doubled elements:", doubled_list)


numbers = [1, 2, 3, 4, 5]

squares = [x**2 for x in numbers]

print(squares)

cubes = [x**3 for x in range(1, 10+1)]

print(cubes)

squares_even = [x**2 for x in range(1, 21) if x % 2 == 0]

print(squares_even)

numbers = [3, 6, 9, 12]

doubled = [x * 2 for x in numbers]

print(doubled)

Here are all the lambda function programs you asked for — simple, clear, and ready to run:

✅ 1. Use a lambda function to find the sum of first 10 numbers


sum_10 = lambda: sum(range(1, 11))
print(sum_10())

✅ 2. Lambda to check if a number is negative


is_negative = lambda x: x < 0
print(is_negative(-5))

✅ 3. Lambda to check if a number is positive


is_positive = lambda x: x > 0
print(is_positive(10))
✅ 4. Lambda to return the length of a string
str_length = lambda s: len(s)
print(str_length("Hello"))

✅ 5. Lambda to add 1 to each element in the list [2, 4, 6, 8]


numbers = [2, 4, 6, 8]
add_one = list(map(lambda x: x + 1, numbers))
print(add_one)

✅ 6. Lambda to check if a number is less than 5


less_than_5 = lambda x: x < 5
print(less_than__5(3))

More Lambda Functions (Set 2)


✅ 1. Lambda to check if a number is odd
is_odd = lambda x: x % 2 != 0
print(is_odd(7))

✅ 2. Lambda to subtract 5 from a number


subtract_5 = lambda x: x - 5
print(subtract_5(20))

✅ 3. Lambda to check if a number is greater than 10


greater_than_10 = lambda x: x > 10
print(greater_than_10(12))

✅ 4. Lambda to check if a number is divisible by 3


div_by_3 = lambda x: x % 3 == 0
print(div_by_3(9))
✅ 5. Lambda to find the sum of two numbers
sum_two = lambda a, b: a + b
print(sum_two(5, 7))

✅ 6. Lambda to check if a number is less than 15


less_than_15 = lambda x: x < 15
print(less_than_15(10))

If you want, I can combine all these into one single program for your notes or practical file!

# Print numbers from 1 to 10 using a for loop

print("Numbers from 1 to 10:")

for i in range(1, 11):

print(i)

# Take integer input from the user

num = int(input("Enter a number: "))

# Check if the number is positive, negative, or zero

if num > 0:

print("Positive")

elif num < 0:

print("Negative")

else:

print("Zero")

Here are all the Python programs you requested — clear, correct, and
ready to use.
✅ 1. Program to check EVEN or
ODD
num = int(input("Enter a number: "))

if num % 2 == 0:
print("Even")
else:
print("Odd")

✅ 2. Program to print all odd


numbers between 1 and 20
for i in range(1, 21):
if i % 2 != 0:
print(i)

✅ 3. Program to print pattern


Pattern:
*
**
***
****
for i in range(1, 5):
print("*" * i)

✅ 4. Program to print all odd


numbers between 1 and 20
(again)
for i in range(1, 21):
if i % 2 != 0:
print(i)

✅ 5. Program to print pattern


Pattern:
1
12
123
1234
12345
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end="")
print()

✅ 6. Program to print numbers


from 10 down to 1
for i in range(10, 0, -1):
print(i)

If you want, I can combine all programs into one single Python file for your
notes!

import math

import random

# -----------------------------------------------------------

# 1. Print numbers from 10 down to 1

# -----------------------------------------------------------

print("Numbers from 10 down to 1:")

for i in range(10, 0, -1):

print(i)

# -----------------------------------------------------------

# 2. Math Functions

# -----------------------------------------------------------

x = 16

y=4
print("\nMath Functions:")

print("Square Root:", [Link](x))

print("Factorial:", [Link](y))

print("Power (x^y):", [Link](2, 5))

print("GCD of 20 and 8:", [Link](20, 8))

print("Round 3.14159 to 2 decimals:", round(3.14159, 2))

# Trigonometric

angle = 30

rad = [Link](angle)

print("\nTrigonometric Functions:")

print("sin(30°):", [Link](rad))

print("cos(30°):", [Link](rad))

print("tan(30°):", [Link](rad))

# -----------------------------------------------------------

# 3. Random Module Examples

# -----------------------------------------------------------

print("\nRandom Module Examples:")

print("Random Integer (1 to 10):", [Link](1, 10))

print("Random Float between 0 and 1:", [Link]())

print("Random Float between 0 and 50:", [Link](0, 50))

my_list = [10, 20, 30, 40, 50]

print("Random Choice:", [Link](my_list))

[Link](my_list)

print("Shuffled List:", my_list)


# -----------------------------------------------------------

# 4. Function for addition and difference (default + positional)

# -----------------------------------------------------------

def add_diff(a, b=5):

add = a + b

diff = a - b

return add, diff

print("\nAddition and Difference (using default & positional arguments):")

print(add_diff(10)) # b defaults to 5

print(add_diff(10, 3)) # both positional

# -----------------------------------------------------------

# 5. Function using keyword arguments

# -----------------------------------------------------------

def multiply(a, b, c):

return a * b * c

print("\nProduct using keyword arguments:")

print(multiply(a=12, b=23, c=34))

# -----------------------------------------------------------

# 6. Function using *args to find maximum

# -----------------------------------------------------------

def find_maximum(*args):

return max(args)

print("\nMaximum using *args:")


print(find_maximum(10, 50, 2, 99, 34))

# -----------------------------------------------------------

# 7. Function using **kwargs to print key-value pairs

# -----------------------------------------------------------

def summarize(**kwargs):

print("\nSummary of keyword arguments:")

for key, value in [Link]():

print(f"{key}: {value}")

summarize(name="John", age=25, country="India")

Below is all the code you requested, written clearly and ready for your practical file.
I will provide:

✅ 1. Function using *args and **kwargs for addition


✅ 2. Package: math_operations ([Link], [Link]) + script
✅ 3. Package: geometric_shapes ([Link]) + script
✅ 4. Package: calculator (basic_operations.py, advanced_operations.py) +
script
✅ 5. While-loop program to sum first n even numbers

✅ **1. Function using *args and


kwargs to perform addition
def add_numbers(*args, **kwargs):
result = 0

for num in args:


result += num

for key, value in [Link]():


result += value

return result
# Example usage
print(add_numbers(2, 4, a=3, b=5)) # Output = 14

✅ 2. Package: math_operations
Folder structure:

math_operations/
__init__.py
[Link]
[Link]
[Link]
[Link]
def add(a, b):
return a + b
[Link]
def subtract(a, b):
return a - b
[Link]
from math_operations.addition import add
from math_operations.subtraction import subtract

print("Addition:", add(10, 5))


print("Subtraction:", subtract(10, 5))

✅ 3. Package: geometric_shapes
Folder structure:

geometric_shapes/
__init__.py
[Link]
triangle_test.py
[Link]
def area(base, height):
return 0.5 * base * height
triangle_test.py
from geometric_shapes.triangle import area

print("Area of triangle:", area(10, 5))

✅ 4. Package: calculator
Folder structure:

calculator/
__init__.py
basic_operations.py
advanced_operations.py
calc_test.py
basic_operations.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b
advanced_operations.py
import math

def square_root(x):
return [Link](x)

def power(x, y):


return [Link](x, y)
calc_test.py
from calculator.basic_operations import add, subtract
from calculator.advanced_operations import square_root, power

print("Add:", add(10, 20))


print("Subtract:", subtract(20, 5))
print("Square Root:", square_root(49))
print("Power:", power(2, 5))

✅ 5. Program: Sum of first n even


numbers using a while loop
n = int(input("Enter a positive integer: "))

sum_even = 0
count = 1
even_number = 2

while count <= n:


sum_even += even_number
even_number += 2
count += 1

print("Sum of first", n, "even numbers is:", sum_even)


If you want, I can combine everything into a single PDF practical file or
create the folders and scripts automatically.

Here are all the programs, neatly divided into sections, ready for your
practical file.
Everything is correct, simple, and beginner-friendly.

✅ LIST COMPREHENSION
PROGRAMS
1. Create a list of numbers from 1 to 5
numbers = [x for x in range(1, 6)]
print(numbers)
2. Create a list of squares for the numbers 2, 3, and 4
squares = [x**2 for x in [2, 3, 4]]
print(squares)
3. First 5 numbers divisible by 2
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)
4. Multiply each number in [1, 2, 3] by 3
result = [x * 3 for x in [1, 2, 3]]
print(result)
5. Add 5 to each number in list from 1 to 5
added = [x + 5 for x in range(1, 6)]
print(added)

✅ FILE HANDLING PROGRAMS


(Basic)
1. Write “Hello, World!” to [Link]
file1 = open("[Link]", "w")
[Link]("Hello, World!")
[Link]()
2. Read and print contents of [Link]
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
✅ FILE HANDLING USING with open()

1. Write to [Link]
with open("[Link]", "w") as f:
[Link]("Hello, World! Good Morning")
2. Copy content from [Link] → [Link]
with open("[Link]", "r") as src:
data = [Link]()

with open("[Link]", "w") as dest:


[Link](data)

✅ EXCEPTION HANDLING
PROGRAMS
1. Division with ZeroDivisionError
try:
a = float(input("Enter numerator: "))
b = float(input("Enter denominator: "))
result = a / b
print("Result:", result)

except ZeroDivisionError:
print("Error: Cannot divide by zero!")

2. Division with ValueError Handling


try:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Result:", a / b)

except ValueError:
print("Error: Please enter numeric values only!")

3. Handle IndexError
lst = [10, 20, 30]

try:
index = int(input("Enter index: "))
print("Value:", lst[index])

except IndexError:
print("Error: Index out of range!")
4. ZeroDivisionError Again (Repeated Requirement)
try:
x = float(input("Enter numerator: "))
y = float(input("Enter denominator: "))
print("Division:", x / y)

except ZeroDivisionError:
print("Error: Denominator cannot be zero!")

✅ ELIF LADDER – STUDENT GRADE


marks = int(input("Enter marks: "))

if marks >= 90:


print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
elif marks >= 60:
print("Grade D")
else:
print("Grade F")

✅ IF–ELIF–ELSE – AGE GROUP


age = int(input("Enter age: "))

if age < 13:


print("Child")
elif age <= 19:
print("Teenager")
elif age <= 59:
print("Adult")
else:
print("Senior Citizen")

✅ SKIP MULTIPLES OF 5 (1 to 100)


for i in range(1, 101):
if i % 5 == 0:
continue
print(i)
If you want, I can combine ALL these into one clean practical PDF or
DOCX file for submission.

You might also like