Wednesday, 8 April 2026

Python Most Used Coding ..SCR's Part _I

 #Define the Function For palindrome
#.palindrome Means Original String =Reverse String 
def is_palindrome(string):
    reversed_string = string[::-1]
    return string == reversed_string
# Test the function
word = input("Enter a word: ")
if is_palindrome(word):
    print(f"{word} is a palindrome")
else:
    print(f"{word} is not a palindrome")

============================================================

# Factorial  2 is Formula n! = n × (n-1)! 2!=2*1
# n!=n×(n−1)×(n−2)×⋯×2×1
#Ex:1*2 =2 then 2*3=6 then 6*4=24 then 24*5=120 then 120*6 #Like that it will work

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
# Test the function
number = int(input("Enter a number: "))
result = factorial(number)
print(f"The factorial of {number} is {result}")

=======================================================================

#Find the largest Number in List
#========== Using Sort  Method=======
numbers = [10, 25, 5, 40, 15]
numbers.sort(reverse=False) # OP:[5, 10, 15, 25, 40]
print(f"Largest Number in List Is  :: {numbers[-1]}") #OP :40
##Find the Second-Largest Number in List
print(f"Second Largest Number in List Is  :: {numbers[-2]}")
# Using Max Function
numbers1 = [10, 25, 5, 40, 15]
numbers1=max(numbers1)
print(f"Largest Number in List Is Using Max  :: {numbers1}")
# Using Loops
numbers2 = [10, 25, 5, 40, 15]
largest = numbers2[0] # Means Its Take 10 Value From List
for num in numbers2: # looping list 
    if num > largest:  # Checking List elements 
        largest = num # Find the Element 
print("Largest element:", largest)

================================================
With Out using Sort Function Sort the String
numbers = [10, 25, 5, 40, 15]
n = len(numbers)
for i in range(n):
    for j in range(0, n-i-1):
        if numbers[j] > numbers[j+1]:
            # Swap
            numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
print("Sorted list:", numbers)

=======================================================================

#Using Python slicing Method
Text= "PYTHON"
S1= Text[::-1]
print(f"Reverse of Word Of {Text}  Is   {S1}")
#Using Reverse Function
text1="MADAm"
reverse_text="".join(reversed(text1))
print(f"Reverse of Word Of {text1}  Is   {reverse_text}")
#Using Loop
text2 =input("Enter a String")#===>Hello
reversed_text = ""
for char in text2:
    reversed_text = char + reversed_text
print("Reversed string:", reversed_text)

==OP===========
Reverse of Word Of PYTHON  Is   NOHTYP
Reverse of Word Of MADAm  Is   mADAM
Enter a StringHello
Reversed string: olleH



Tuesday, 7 April 2026

Using generator producing Fibonacci numbers


   
 def fun():
    a,b=
0,1 ---> Define Variables
while b<10: Using While Loop
yield b -- Using Generator Yiled Hear
a,b=b,a+b -- Logic Of Fab


i2=fun() -- Creating object
for i in i2: ---> Using loop
print(i,end=" ")



Output:
1 1 2 3 5 8

Monday, 30 March 2026

Print the Sum of Number in range in python

 #Print the Sum of Number in range
#0,1,2,3,4,5,6,7,8,9,10
#0+1+2+3+4+5+6+7+8+9+10=55
num=int(input("Enter a number: "))
print(sum(i for i in range(1,num+1)))#--->Logic

Sunday, 29 March 2026

For Loop In Python zero to Hero

 For Loop In Python zero to Hero


Loop Means = repeat code multiple times

for Loop:  Used when you know how many times to repeat code 

#Let’s say you have a list of numbers, and you want to print each number.

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

hear Code 
                for number in numbers:
                        print(number)
#numbers is the sequence, which in this case is a defined list of numbers
#number is the loop variable that takes each value from the list, one at a time.
#print(number) is a statement in the code block that gets executed for each item in the list


Ranges and for loops
The range() function in Python generates a sequence of numbers. It is commonly used in for loops to iterate over a sequence of numbers. The range() function can take one, two, or three arguments:
range(stop): generates numbers from 0 to stop – 1.
range(start, stop): generates numbers from start to stop – 1.
range(start, stop, step): generates numbers from start to stop – 1, incrementing by step.

I want 5 Mulipcation Table

Number =5 table upto_means number range loop will excute tell them example i am giveing 11 menas 
5
.
.
.
50  range ok but i want table change Print Function  
number=int(input("Enter a number: "))
up_to=int(input("Enter a number: "))
for i in range(1, up_to):
print(f"{number} x {i} = {number * i}")
Output:
Enter a number: 5
Enter a number: 11
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Statements: break and continue with for loops


The break statement allows you to exit the loop before it is completed. When the break statement is executed, the loop terminates immediately, and the program continues with the next statement following the loop.

The continue statement allows skipping the current iteration of a loop and proceeding to the next iteration. When the continue statement is encountered, the next iteration begins

items = ['apple', 'banana', 'cherry', 'date', 'elderberry']

search_item = 'cherr'

for item in items:

    if item == search_item:

        print(f'Found {search_item}!')

        break

# Optional else clause

else:

    print(f'{search_item} not found.')

=======================================================

items1 = ['apple', 'banana', 'cherry', 'lemon', 'elderberry']

for items in items1:

    if 'a' in items:

        continue

    print(items)

================================================

In Python, enumerate() is a built-in function that adds a counter to an iterated item and returns it as an enumerated object. This can be especially useful for looping over a list, or any other item where both the index and the value of each item are needed.

As a developer, you can use these functions to make your code more readable and concise by eliminating the need to manually manage counter-variables. They also help reduce the risk of errors that can occur when manually incrementing a counter.

Here’s a simple example to illustrate how enumerate() can be used in a for loop:

# List of fruits

fruits = ['apple', 'banana', 'cherry']

# Using enumerate to get index and value

for index, fruit in enumerate(fruits, start=0   ):

    print(f"{index}: {fruit}")

===============================================

Real time Usage:=

In the following loop example, you can use a loop to automate processing files. The following loop scans a directory, separates files from folders, and provides a list of all the files inside with their local path.

import os


directory = '/path/to/directory'


# Iterate over all files in the directory


for filename in os.listdir(directory):


    file_path = os.path.join(directory, filename)


    if os.path.isfile(file_path):


        print(f'File: {filename, file_path}')


/path/to/directory is a placeholder to be replaced with the local path for the directory to be processed.

os.listdir(directory) lists all the entries in the specified directory.

os.path.join(directory, filename) constructs the full path to the file.

os.path.isfile(file_path) checks if the path is a file (and not a directory).

Knowing the exact location of files helps create precise backups and restore them when needed.

Pattern Prints in For loop

:#Pyramid Pattern (Important 🔥)

n = 5
for i in range(1, n+1):
print(" " * (n-i) + "*" * (2*i-1))

Output:-

 *

   ***

  *****

 *******

*********



Pprint & Pformat in Python

 If you import the pprint module into your programs, you’ll have access to the pprint() and pformat() functions that will “pretty print” a dictionary’svalues. This is helpful when you want a cleaner display of the items in a dictionary than what print() provides.

import pprint

message = "It was a bright cold day in April, and the clocks were striking thirteen."
count = {}
for character in message:
count.setdefault(character,
0)
count[character] = count[character] +
1
pprint.pprint(count)

The pprint.pprint() function is especially helpful when the dictionary itself contains nested lists or dictionaries. If you want to obtain the prettified text as a string value instead of displaying it on the screen, call pprint.pformat() instead. These two lines are equivalent to each other:

Friday, 20 March 2026

Deep in Python list

 

Most Important in Python(0-Z)

1.What is List. Explain in Detail

         The list class is a fundamental built-in data type in Python        

Ø  Ordered: They contain elements or items that are sequentially arranged according to their specific insertion order.

Ø  Zero-based: They allow you to access their elements by indices that start from zero.

Ø  Mutable: They support in-place mutations or changes to their contained elements.

Ø  Heterogeneous: They can store objects of different types.

Ø  Growable and dynamic: They can grow or shrink dynamically, which means that they support the addition, insertion, and removal of elements.

Ø  Nestable: They can contain other lists, so you can have lists of lists.

Ø  Iterable: They support iteration, so you can traverse them using a loop or comprehension while you perform operations on each of their elements.

Ø  Sliceable: They support slicing operations, meaning that you can extract a series of elements from them.

Ø  Combinable: They support concatenation operations, so you can combine two or more lists using the concatenation operators.

In Python, lists are ordered, which means that they keep their elements in the order of insertion

 

Ex: a = [1, 2, 3, 4]

         shopping = ["Milk", "Eggs", "Bread"]

         list_name = [item1, item2, item3]

List is Mutable (VERY IMPORTANT)

👉 You can modify list after creation

Ex:-

Indexing (in List Access Elements):-

You can access an individual object in a list by its position or index in the sequence. Indices start from zero:

Synatx :list_object[index]

           Ex:list[0] – acess First Element in List

 

Type in Command Each below:-

course=["P","Y","T","H","O","N"]
print(course)
#Access First element in List
print("Access First element in List",course[0])
#Access last element in List
print("Access last element in List",course[-1])
#Above statement i don't know string elements that y use this one
print("Access last element in List",course[5])
#Above statement i  know string elements that y use this one
print("Access last using len function element in List",course[len(course)-1])
#aceess First two elements from list
print("Access last element in List",course[0,1]) --error Beasuce Index not work

Slicling:-

Retrieving Multiple Items From a List: Slicing

Syntax:- list_object[start:stop:step]

The [start:stop:step] part of this construct is known as the slicing operator. Its syntax consists of a pair of square brackets and three optional indices, start, stop, and step. The second colon is optional. You typically use it only in those cases where you need a step value different from 1.

  • start specifies the index at which you want to start the slicing. The resulting slice includes the item at this index.
  • stop specifies the index at which you want the slicing to stop extracting items. The resulting slice doesn’t include the item at this index.
  • step provides an integer value representing how many items the slicing will skip on each step. The resulting slice won’t include the skipped items.

                                  Index                           Default Value

                                  start                                    0

                                  stop                         len(list_object)

                                  step                                       1

Example:

letters = ["A", "a", "B", "b", "C", "c", "D", "d"]

I want Upper case letter From List

Index start with hear à0

Stop hear d(Means 8)

Step 2 counter

upper_letters = letters[0::2] –smart way

letters = ["A", "a", "B", "b", "C", "c", "D", "d"]
uppercase=letters[0:8:2]  --Understanding Way this also give same result
print(uppercase)

 

Home work Lower Case you Can try :

 

Pro Level:-

digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#0 to 5 from list
print(digits[0:4]) # Res [0, 1, 2, 3]
print(digits[:4])  # Res [0, 1, 2, 3]
print(digits[-4:]) #res [6, 7, 8, 9]
print(digits[0:len(digits):2]) #res [0, 2, 4, 6, 8]
course=["P","Y","T","H","O","N"]
print(course[::-1]) # res ['N', 'O', 'H', 'T', 'Y', 'P']--revse String

To change the value of a given element in a list, you can use the following syntax:

list_object[index] = new_value

 

In Python, you’ll have two kinds of mechanisms to create copies of an existing list. You can create either:

1.   shallow copy

2.   deep copy

Both types of copies have specific characteristics that will directly impact their behaviour. In the following sections, you’ll learn how to create shallow and deep copies of existing lists in Python. First, you’ll take a glance at aliases, a related concept that can cause some confusion and lead to issues and bugs.

Methods in list:

List Methods

Let's look at different list methods in Python:

  • append(): Adds an element to the end of the list.

Syntax: list_name.append(element)

  • copy(): Returns a shallow copy of the list.

         Syntax: list_name.copy()

  • clear(): Removes all elements from the list.

Syntax: list_name.clear()

  • count(): Returns the number of times a specified element appears in the list.

         Syntax: list_name.count(element)

  • extend(): Adds elements from another list to the end of the current list.

         Syntax: list_name.extend(iterable)

  • index(): Returns the index of the first occurrence of a specified element.

Syntax: list_name.index(element)

  • insert(): Inserts an element at a specified position.

         Syntax: list_name.insert(index, element)

  • pop(): Removes and returns the element at the specified position (or the last element if no index is specified).

Syntax: list_name.pop(index)

  • remove(): Removes the first occurrence of a specified element.

Syntax: list_name.remove(element)

  • reverse(): Reverses the order of the elements in the list.

         Syntax: list_name.reverse()

  • sort(): Sorts the list in ascending order (by default).

Syntax: list_name.sort(key=None, reverse=False)

 

 

Max , Min,and there or more find your self map filter alos those this  your home work

 

 

 

 

 

 

 

 

 

 

Tuesday, 17 March 2026

Python list Interview Q&A

 #----------------List Interview Question For Zero to Adv Level--------

# Reverse a list

number=[10,30,20,40,60,90,80,100]

# using sort and reverse keyword we can use

number.sort(reverse=True)

print(number) # result [100, 90, 80, 60, 40, 30, 20, 10]

number1=[10,30,20,40,60,90,80,100]

#without Sort and reverse key word

print(number1[::-1]) #result [100, 80, 90, 60, 40, 20, 30, 10]

#2. Find largest & smallest

number2=[10,30,20,40,60,90,80,100]

print(max(number2)) # Max Number is 100

print(min(number2)) # Min Number is 10

print(sum(number2)) # Sum of Number is 430

#3.Count occurrences

number2=[10,30,20,40,20,20,20,60,90,80,100]

print(number2.count(20)) # Result is 4

#4.Remove duplicates

print(list(set(number2))) #[100, 40, 10, 80, 20, 90, 60, 30]

#5 Second_largest number in list

L1=list(set(number2)) # Remove Duplicates

L1.sort() # sort the List

print(L1[-2]) # Find the Second_Highest Number

mylist = ['apple', 'banana', 'cherry']

mylist[1:2] = ['kiwi', 'mango']

print(mylist) 

print(mylist[2])



Python Most Used Coding ..SCR's Part _I

 #Define the Function For palindrome #.palindrome Means Original String =Reverse String  def is_palindrome(string):     reversed_string = st...