Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Common coding mistake in Python

how to check particular char of string in list available or not

invalid syntax mistake

for char in original_string
    if char in characters_to_remove:
Enter fullscreen mode Exit fullscreen mode

Image description

solution
put colon after for
Note put colon after for ,def ,if,else
Note remember the indention of for,if,else and pass
indention of for and if

for char in original_string:
    if char in characters_to_remove:
Enter fullscreen mode Exit fullscreen mode

indention for,if and data

for newdata in data:
    if newdata%2 == 0:
        even.append(newdata)
Enter fullscreen mode Exit fullscreen mode

Indention between for,if and local print global print

even = []

for newdata in data:
    if newdata%2 == 0:
        even.append(newdata)
        print(newdata)
print(even)
Enter fullscreen mode Exit fullscreen mode

indention between for,if,else,print

for max_data in words_list:
    if maxdatas>max_data:
       maxdatas=maxdatas
    else:
         maxdatas=max_data
print(maxdatas)
Enter fullscreen mode Exit fullscreen mode

indention between for,if,else,pass,print

for max_data in words_list:
    if maxdatas>max_data:
       pass
    else:
         pass
print(maxdatas)
Enter fullscreen mode Exit fullscreen mode

IndentationError: expected an indented block
Indention error b/w double for block

data = (4,6,9,10)
list=[]

for char in data:
    if char%2==0:
       list.append(char)

    for lits in list:

    print("Original String:", lits)
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data = (4, 6, 9, 10)
my_list = []

for number in data:
    if number % 2 == 0:
        my_list.append(number)

for item in my_list:
    print("Original String:", item)
Enter fullscreen mode Exit fullscreen mode

wrong

def add():
    data="python"
    my=["o","n"]
    new=[]
    for newdata in data
    if my in newdata
Enter fullscreen mode Exit fullscreen mode

Correct
always iterate in string,list,dictionary,tuple not single variable of list

if newdata in my
Enter fullscreen mode Exit fullscreen mode
def add():
    data="python"
    my=["o","n"]
    new=[]
    for newdata in data
    if newdata in my
Enter fullscreen mode Exit fullscreen mode

How to add new char in empty string or exisiting string without for loop

empty_string = ""  # An empty string

new_char1 = "Hello, "
new_char2 = "world!"

# Concatenating strings
new_string = empty_string + new_char1 + new_char2

# Using the += operator
empty_string += new_char1
empty_string += new_char2

print("Empty String:", empty_string)
print("New String after adding characters:", new_string)
Enter fullscreen mode Exit fullscreen mode

How to add new char in empty string or exisiting string inside for loop

data = "python"
vowels = "aeiou"
mynew = ""

for char in data:
    if char not in vowels:
        mynew += char
Enter fullscreen mode Exit fullscreen mode

==========================================================
1.Wap print those name that contain letters n

my=["ram","rana","rina","sham","raddhe"]
letters="n"
lists=[]
for data in my:
    if letters in data:
        lists.append(data)
print(lists)
Enter fullscreen mode Exit fullscreen mode

output

['rana', 'rina']  
Enter fullscreen mode Exit fullscreen mode

=======OR=========

my = ["ram", "rana", "rina", "sham", "raddhe"]
letters = "n"

# Printing the elements containing the specified letters directly within the loop
for data in my:
    if letters in data:
        print(data)
Enter fullscreen mode Exit fullscreen mode

output

rana
rina
Enter fullscreen mode Exit fullscreen mode

2.Wap print those name that not contain letters n

my=["ram","rana","rina","sham","raddhe"]
letters="n"
lists=[]
for data in my:
    if letters in data:
        pass
    else:
        lists.append(data)
print(lists)  
Enter fullscreen mode Exit fullscreen mode

output

['ram', 'sham', 'raddhe']
Enter fullscreen mode Exit fullscreen mode

3.Wap to remove vowels from string

data = "python"
vowels = "aeiou"
mynew = ""

for char in data:
    if char not in vowels:
        mynew += char
print(mynew) 
Enter fullscreen mode Exit fullscreen mode

output

pythn
Enter fullscreen mode Exit fullscreen mode

4.Wap to replace vowels from single letters string

data = "python"
vowels = "aeiou"
mynew = ""

for char in data:
    if char not in vowels:
        mynew += char
    else:
        mynew += "h"      
print(mynew)
Enter fullscreen mode Exit fullscreen mode

output

pythhn
Enter fullscreen mode Exit fullscreen mode

=========OR=========
Using replace
NOTE: can achive without creating new string like mynew in above prog

data = "python"
vowels = "aeiou"
for char in data:
    if char not in vowels:
        pass
    else:
        newdata=data.replace(char,"h")
print(newdata)
Enter fullscreen mode Exit fullscreen mode

Output

pythhn
Enter fullscreen mode Exit fullscreen mode

==============OR===============
Using sub

import re
data = "python"
vowels = "aeiou"
mychar="t"
for char in data:
    if char not in vowels:
        pass
    else:
         data=re.sub(char, "h", data)
print(data)
Enter fullscreen mode Exit fullscreen mode

output

pythhn
Enter fullscreen mode Exit fullscreen mode

5.Wap to print those name from list that does not contain vowel letters

my_list = ["Asm", "rana", "rina", "sham", "raddhe", "btm"]

names_without_vowels = []

for name in my_list:
    has_vowel = False
    for char in name:
        if char.lower() in 'aeiou':
            has_vowel = True
            break
    if not has_vowel:
        names_without_vowels.append(name)

print("Names without any vowel letters:", names_without_vowels)
Enter fullscreen mode Exit fullscreen mode

output

Names without any vowel letters: ['btm']
Enter fullscreen mode Exit fullscreen mode

6.Create a class named Book where title,publishers,price act as a data member along with caldiscount function that calculates the given discount on book price. Also create displaydata function that will call caldiscount function and display all the values. Take discount=15 as class variable

class Book:
    discount = 15  # Class variable for discount percentage

    def __init__(self, title, publisher, price):
        self.title = title
        self.publisher = publisher
        self.price = price

    def caldiscount(self):
        # Method to calculate discount on book price
        discount_amount = (self.discount / 100) * self.price
        discounted_price = self.price - discount_amount
        return discounted_price

    def displaydata(self):
        # Method to display book details including discounted price
        discounted_price = self.caldiscount()
        print("Title:", self.title)
        print("Publisher:", self.publisher)
        print("Price:", self.price)
        print("Discounted Price:", discounted_price)


# Example usage:
book1 = Book("Python Programming", "ABC Publications", 500)
book1.displaydata()
Enter fullscreen mode Exit fullscreen mode

output

Title: Python Programming
Publisher: ABC Publications
Price: 500
Discounted Price: 425.0
Enter fullscreen mode Exit fullscreen mode

**7.Define a class CONTAINER in Python with the following specifications: -Instance Attributes

  • Radius,Height # Radius and Height of Container -Volume # Volume of Container Methods
  • CalVolume() # Method to calculate volume # # With the formula as given below 3.14* Radius * Height
  • GetValue() # Method to allow user to enter values of # Radius and Height # Also, this method should call # CalVolume() method to calculate Volume
  • ShowContainer() # To display Radius, Height and Volume**
class CONTAINER:
    def __init__(self):
        self.radius = 0  # Initialize radius attribute
        self.height = 0  # Initialize height attribute
        self.volume = 0  # Initialize volume attribute

    def CalVolume(self):
        # Method to calculate volume using the given formula
        self.volume = 3.14 * self.radius * self.height

    def GetValue(self):
        # Method to allow user to enter values of radius and height
        self.radius = float(input("Enter the radius of the container: "))
        self.height = float(input("Enter the height of the container: "))
        self.CalVolume()  # Call CalVolume method to calculate volume

    def ShowContainer(self):
        # Method to display radius, height, and volume
        print("Radius:", self.radius)
        print("Height:", self.height)
        print("Volume:", self.volume)

# Create an instance of the CONTAINER class
container = CONTAINER()

# Get values from the user and display container details
container.GetValue()
container.ShowContainer()
Enter fullscreen mode Exit fullscreen mode

output

Image description
press enter

Image description

press enter

Enter the radius of the container: 6
Enter the height of the container: 8
Radius: 6.0
Height: 8.0
Volume: 150.72
Enter fullscreen mode Exit fullscreen mode

8. combine two dictionary

dict1 = {'Mercury': 100, 'Venus': 200, 'Earth': 300}
dict2 = {'Star': 500, 'Moon': 600, 'Sun': 700}

dict1.update(dict2)

print(dict1)
Enter fullscreen mode Exit fullscreen mode

output

{'Mercury': 100, 'Venus': 200, 'Earth': 300, 'Star': 500, 'Moon': 600, 'Sun': 700}
Enter fullscreen mode Exit fullscreen mode

9.remove particular key value pair from dictionary

ages = {"Alice": 30, "Bob": 25, "Charlie": 35, "David": 40}

# Removing the age associated with "Charlie"
removed_age = ages.pop("Charlie")
print("Removed age:", removed_age)
print("Updated dictionary:", ages)
Enter fullscreen mode Exit fullscreen mode

output

Removed age: 35
Updated dictionary: {'Alice': 30, 'Bob': 25, 'David': 40}
Enter fullscreen mode Exit fullscreen mode

10.Rename key city to location in the following dictionary
sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city": "New york"}
Expected output: { "name": "Kelly", "age":25, "salary": 8000, "location": "New york"}

sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city": "New york"}

# Rename the key from "city" to "location"
sampleDict["location"] = sampleDict.pop("city")

print(sampleDict)
Enter fullscreen mode Exit fullscreen mode

output

{ "name": "Kelly", "age":25, "salary": 8000, "location": "New york"}
Enter fullscreen mode Exit fullscreen mode

11.Write a class circle to calculate the area of it

import math

class Circle:
    def __init__(self, x):
        self.x = x

    def area(self):
        return math.pi * self.x ** 2

x = 5
data = Circle(x)
print("Area of circle:", data.area())
Enter fullscreen mode Exit fullscreen mode

output

Area of circle: 78.53981633974483
Enter fullscreen mode Exit fullscreen mode

12.create a instance of class and print it

class MyClass:
    def __init__(self, x):
        self.x = x  # Assigning instance variable x using self

    def print_value(self):
        print("Value of x:", self.x)  # Accessing instance variable x using self

obj1 = MyClass(5)  # Creating an instance of MyClass
obj2 = MyClass(10)  # Creating another instance of MyClass

obj1.print_value()  # Calling print_value method on obj1
obj2.print_value()  # Calling print_value method on obj2
Enter fullscreen mode Exit fullscreen mode

output

Value of x: 5
Value of x: 10
Enter fullscreen mode Exit fullscreen mode

13.Write a program asks for City name and Temperature and builds a dictionary using that Later on you can input City name and it will tell you the Temperature of that City.

temperature_data = {}  # Dictionary to store city names and temperatures

# Function to add city name and temperature to the dictionary
def add_temperature():
    city = input("Enter the city name: ")
    temperature = input("Enter the temperature for {} in Celsius: ".format(city))
    temperature_data[city] = temperature
    main()  # Call main function again to display menu

# Function to retrieve temperature of a given city
def get_temperature():
    city = input("Enter the city name to get temperature: ")
    if city in temperature_data:
        print("Temperature in {} is {} Celsius.".format(city, temperature_data[city]))
    else:
        print("Temperature data for {} not found.".format(city))
    main()  # Call main function again to display menu

# Main function to display menu and handle user input
def main():
    print("\n1. Add Temperature Data")
    print("2. Get Temperature")
    print("3. Exit")

    choice = input("Enter your choice (1/2/3): ")

    if choice == '1':
        add_temperature()
    elif choice == '2':
        get_temperature()
    elif choice == '3':
        print("Exiting program.")
    else:
        print("Invalid choice. Please enter a valid option.")
        main()  # Call main function again if choice is invalid

# Call main function to start the program
main()
Enter fullscreen mode Exit fullscreen mode

output

Image description

SOME COMMON REGX QUESTION

What does the split() function do in Python?
split() function splits a string into a list of substrings based on a specified delimiter.

text = "apple, banana, cherry"
fruits = text.split(", ")
print(fruits)  # Output: ['apple', 'banana', 'cherry']
Enter fullscreen mode Exit fullscreen mode

How do you split a string into words using split()?
You can split a string into words by specifying a space as the delimiter.

text = "Hello world, how are you?"
words = text.split()
print(words)  # Output: ['Hello', 'world,', 'how', 'are', 'you?']
Enter fullscreen mode Exit fullscreen mode

============OR=============
Using findall

import re
text = "Hello, world! This is a test."
words = re.findall(r'\w+', text)
print(words)  # Output: ['Hello', 'world', 'This', 'is', 'a', 'test']
Enter fullscreen mode Exit fullscreen mode

How do you split a string into lines using splitlines()?
You can split a multiline string into lines using the splitlines() method.

text = "Line 1\nLine 2\nLine 3"
lines = text.splitlines()
print(lines)  # Output: ['Line 1', 'Line 2', 'Line 3']
Enter fullscreen mode Exit fullscreen mode

What does the replace() function do in Python?
replace() function replaces all occurrences of a substring in a string with another substring.

text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)  # Output: "Hello, Python!"
Enter fullscreen mode Exit fullscreen mode

How do you replace multiple substrings in a string using replace()?
You can chain multiple replace() calls to replace multiple substrings.

text = "Hello, World! Hello, World!"
new_text = text.replace("Hello", "Hi").replace("World", "Python")
print(new_text)  # Output: "Hi, Python! Hi, Python!"
Enter fullscreen mode Exit fullscreen mode

How do you remove all spaces from a string using replace()?
You can replace all spaces with an empty string to remove them.

text = "Hello  World"
new_text = text.replace(" ", "")
print(new_text)  # Output: "HelloWorld"
Enter fullscreen mode Exit fullscreen mode

How do you replace digits in a string with X using regex?
You can use re.sub() with a regex pattern to replace digits with X.

import re
text = "There are 123 apples and 456 oranges."
new_text = re.sub(r'\d', 'X', text)
print(new_text)  # Output: "There are XXX apples and XXX oranges."
Enter fullscreen mode Exit fullscreen mode

How do you split a string at uppercase letters using regex?
You can use a regex pattern to split a string at uppercase letters.

import re
text = "SplitAtUpperCaseLetters"
parts = re.findall(r'[A-Z][^A-Z]*', text)
print(parts)  # Output: ['Split', 'At', 'Upper', 'Case', 'Letters']
Enter fullscreen mode Exit fullscreen mode

How do you split a string at non-alphanumeric characters using regex?
You can use a regex pattern to split a string at non-alphanumeric characters.

import re
text = "Split, at non-alphanumeric characters!"
parts = re.split(r'\W+', text)
print(parts)  # Output: ['Split', 'at', 'non', 'alphanumeric', 'characters']
Enter fullscreen mode Exit fullscreen mode

How do you replace a specific word in a string using regex?
You can use re.sub() with a regex pattern to replace a specific word

import re
text = "Replace this word with another."
new_text = re.sub(r'\bword\b', 'phrase', text)
print(new_text)  # Output: "Replace this phrase with another."
Enter fullscreen mode Exit fullscreen mode

How do you extract all hashtags from a string using rege?
You can use a regex pattern to match hashtags in a string.

import re
text = "This is a #sample text with #hashtags."
hashtags = re.findall(r'#\w+', text)
print(hashtags)  # Output: ['#sample', '#hashtags']
Enter fullscreen mode Exit fullscreen mode

How do you extract all capitalized words from a string using regex?

import re
text = "This is A Test String With CAPITALIZED WORDS."
capitalized_words = re.findall(r'\b[A-Z][a-z]*\b', text)
print(capitalized_words)  # Output: ['This', 'Test', 'String', 'With', 'CAPITALIZED', 'WORDS']
Enter fullscreen mode Exit fullscreen mode

What does the re.findall() function do in Python?
re.findall() returns a list of all non-overlapping matches of a pattern in a string.

import re
text = "apple, banana, cherry, banana, orange"
pattern = "banana"
matches = re.findall(pattern, text)
print(matches)  # Output: ['banana', 'banana']
Enter fullscreen mode Exit fullscreen mode

How do you find all numbers in a string using regex?
You can use \d+ pattern to find all numbers (sequences of digits) in a string.

import re
text = "The price is $10 for item 1, $20 for item 2, and $30 for item 3."
numbers = re.findall(r'\d+', text)
print(numbers)  # Output: ['10', '1', '20', '2', '30', '3']
Enter fullscreen mode Exit fullscreen mode

How do you replace all occurrences of a pattern in a string using regex?
You can use the re.sub() function to replace all occurrences of a pattern in a string.

import re
text = "apple, banana, cherry"
pattern = "banana"
replacement = "grape"
new_text = re.sub(pattern, replacement, text)
print(new_text)  # Output: "apple, grape, cherry"
Enter fullscreen mode Exit fullscreen mode

How do you extract all capitalized words from a string using regex?
You can use a regex pattern to match capitalized words in a string.

import re
text = "This is A Test String With CAPITALIZED WORDS."
capitalized_words = re.findall(r'\b[A-Z][a-z]*\b', text)
print(capitalized_words)  # Output: ['This', 'Test', 'String', 'With', 'CAPITALIZE']
Enter fullscreen mode Exit fullscreen mode

How do you extract all hashtags from a string using regex?
You can use a regex pattern to match hashtags in a string.

import re
text = "This is a #sample text with #hashtags."
hashtags = re.findall(r'#\w+', text)
print(hashtags)  # Output: ['#sample', '#hashtags']
Enter fullscreen mode Exit fullscreen mode

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

Apply lambda function

Apply lambda function

===============================================================
print in new line or in list observe

data = [4, 16, 9, 20]

even = []

for newdata in data:
    if newdata%2 == 0:
        print(newdata)
Enter fullscreen mode Exit fullscreen mode

output

Image description

data = [4, 16, 9, 20]

even = []

for newdata in data:
    if newdata%2 == 0:
        even.append(newdata)
print(even)  
Enter fullscreen mode Exit fullscreen mode

output

Image description

wrong
dont put gap b/w + and = operator

data="python"  
vowel=["a","i","o","e","u"]
mynew=""
for mydata in data:
    if mydata not in vowel:
       mynew + = mydata
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data="python"  
vowel=["a","i","o","e","u"]
mynew=""
for mydata in data:
    if mydata not in vowel:
       mynew += mydata
Enter fullscreen mode Exit fullscreen mode
data = (4, 6, 9, 10)
my_list = []

for number in data:
    if number % 2 == 0:
        my_list.append(number)
print("Original String:", my_list)
for item in my_list:
    print("Original String:", item)
Enter fullscreen mode Exit fullscreen mode

wrong:

data = (4, 6, 9, 10)
my_list = []

for number in range(len(data)):
    if number % 2 == 0:
        my_list.append(number)
print("Original String:", my_list)
for item in my_list:
    print("Original String:", item)
Enter fullscreen mode Exit fullscreen mode

Solution
iterate over the indices and then access the elements whenever you use range

data = (4, 6, 9, 10)
my_list = []

for index in range(len(data)):
    if data[index] % 2 == 0:
        my_list.append(data[index])

print("Original List of Even Numbers:", my_list)

for item in my_list:
    print("Even Number:", item)
Enter fullscreen mode Exit fullscreen mode

wrong

data={"name":"rakesh","age":33}
name=data[name]
print(name)
Enter fullscreen mode Exit fullscreen mode

Image description

correct
whenever string is in dictionary to access its value use double quotes

data={"name":"rakesh","age":33}
name=data["name"]
print(name)
Enter fullscreen mode Exit fullscreen mode

wrong

Image description

# Online Python - IDE, Editor, Compiler, Interpreter
list=[5,8,6,7]
name=[elementname for data in list if 5==data]
print(name)
Enter fullscreen mode Exit fullscreen mode

wrong

Image description

# Online Python - IDE, Editor, Compiler, Interpreter
list=[5,8,6,7]
name=[data for data in list if element==data]
print(name)
Enter fullscreen mode Exit fullscreen mode

correct

# Online Python - IDE, Editor, Compiler, Interpreter
list=[5,8,6,7]
name=[data for data in list if 5==data]
print(name)
Enter fullscreen mode Exit fullscreen mode

Image description

wrong

data = {"name": "rakesh", "age": 33}
name = data["name"]
data["hobby"] = "readingbooks"

for key, value in data.items():
    print(key value)
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data = {"name": "rakesh", "age": 33}
name = data["name"]
data["hobby"] = "readingbooks"

for key, value in data.items():
    print(key, value)
Enter fullscreen mode Exit fullscreen mode
data = {"name": "rakesh", "age": 33}
name = data["name"]
data["hobby"] = "readingbooks"

for key, value in data.items():
    print(key, ":", value)
Enter fullscreen mode Exit fullscreen mode

wrong

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=null
for key, value in data.items():
    cost +=value
print(cost)
Enter fullscreen mode Exit fullscreen mode

Image description

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=""
for key, value in data.items():
    cost +=value
print(cost) 
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=0
for key, value in data.items():
    cost +=value
print(cost) 
Enter fullscreen mode Exit fullscreen mode

wrong
RuntimeError: dictionary changed size during iteration

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=0
for key, value in data.items():
   data["guava"]=40
print(cost) 
Enter fullscreen mode Exit fullscreen mode

Image description

correct

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
cost=0
update={}
for key, value in data.items():
   update["guava"]=40
   cost +=value
data.update(update)   
print(data,":",cost)
Enter fullscreen mode Exit fullscreen mode

Declaration of empty datatype to create or append to create new

dict={}   // dict[char] +=number  or  dict[char] ="word
list=[]  //list.append(data)
string=""  // create new string mynew + = mydata
number=0   // create new string dict[char]+ = number
result_even = {'even': []}//{"group1": [1, 2, 3]}
result_dict = {'odd': {}, 'even': {}}
 result_dict[key] = []
Enter fullscreen mode Exit fullscreen mode

image

Image description

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

Image description

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

Image description

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

Image description

TIPS

any data type dictionary,set,tuple convert in list using list comprhension then whatever fun u r applying in list u can apply in list comprhension below sum and len fun is applying on list comprhension

Image description

Wrong
how to search particular value based on key

contacts_dict = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Charlie": "charlie@example.com",
}
name_to_lookup = "Bob"
search=""
for key,value in contacts_dict.items():
    if contacts_dict[key]==name_to_lookup:
       search=contacts_dict[value]
print(search)
Enter fullscreen mode Exit fullscreen mode

wrong

Image description

Correct

contacts_dict = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Charlie": "charlie@example.com",
}
name_to_lookup = "charlie@example.com"
search=""
for key,value in contacts_dict.items():
    if contacts_dict[key]==name_to_lookup:
       search=contacts_dict[key]
print(search)
Enter fullscreen mode Exit fullscreen mode

output

charlie@example.com

grouped_dict = {
    "group1": [1, 2, 7, 3],
    "group2": [4, 5, 5, 6],
    "group3": [7, 8, 9, 8]
}

target_value = 5

locations = [index for group, elements in grouped_dict.items() for index, value in enumerate(elements) if value == target_value]

if locations:
    print(f"The value {target_value} is located in the following places:")
    for location in locations:
        print(f"Group '{location[0]}' at index {location[1]}")
else:
    print(f"The value {target_value} is not found in the dictionary.")
Enter fullscreen mode Exit fullscreen mode

Correct

grouped_dict = {
    "group1": [1, 2, 7, 3],
    "group2": [4, 5, 5, 6],
    "group3": [7, 8, 9, 8]
}

target_value = 5

locations = [(group, index) for group, elements in grouped_dict.items() for index, value in enumerate(elements) if value == target_value]

if locations:
    print(f"The value {target_value} is located in the following places:")
    for location in locations:
        print(f"Group '{location[0]}' at index {location[1]}")
else:
    print(f"The value {target_value} is not found in the dictionary.")
Enter fullscreen mode Exit fullscreen mode

Image description

wrong

Image description
dict_item[word]=data

# Online Python - IDE, Editor, Compiler, Interpreter
listing=["apple","banana","peru","mango"]
dict_item={}
length=0
for data in listing:
    word=len(data)
    if word not in dict_item:
       dict_item[word]=data
    else:   
       dict_item[word].append(data)
print(dict_item)
Enter fullscreen mode Exit fullscreen mode

correct

# Online Python - IDE, Editor, Compiler, Interpreter
listing=["apple","banana","peru","mango"]
dict_item={}
length=0
for data in listing:
    word=len(data)
    if word not in dict_item:
       dict_item[word]=[data]
    else:   
       dict_item[word].append(data)
print(dict_item)
Enter fullscreen mode Exit fullscreen mode

=========or==========

# Online Python - IDE, Editor, Compiler, Interpreter
listing=["apple","banana","peru","mango"]
dict_item={}
length=0
for data in listing:
    word=len(data)
    if word not in dict_item:
       dict_item[word]=[]

    dict_item[word].append(data)
print(dict_item)
Enter fullscreen mode Exit fullscreen mode

Image description

wrong

contacts_dict = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Charlie": "charlie@example.com",
}
name_to_lookup = "Bob"
search = ""
for data in contacts_dict:
    if contacts_dict[data] == name_to_lookup:
        search = contacts_dict[data]
print(search)
Enter fullscreen mode Exit fullscreen mode

Correct

contacts_dict = {
    "Alice": "alice@example.com",
    "Bob": "bob@example.com",
    "Charlie": "charlie@example.com",
}
name_to_lookup = "Bob"
search = ""

for key, value in contacts_dict.items():
    if key == name_to_lookup:
        search = value

print(search)
Enter fullscreen mode Exit fullscreen mode

output

bob@example.com
Enter fullscreen mode Exit fullscreen mode

two ways to find sum of value in list

my_list = [8, 9, 7, 9, 56]
sum=0
for data in my_list:
    sum +=data
print(sum)
Enter fullscreen mode Exit fullscreen mode

2nd way

my_list = [8, 9, 7, 9, 56]
new_sum = sum(my_list)
Enter fullscreen mode Exit fullscreen mode

two way to access if dictionary contain only keys

data = {"name", "age"}

for news in data:
    print(news)
Enter fullscreen mode Exit fullscreen mode

Image description

data = {"name", "age"}

# Convert the set to a list
data_list = list(data)

# Access the first element
first_element = data_list[0]

print(first_element)
Enter fullscreen mode Exit fullscreen mode

output

Image description

wrong

data = {"name", "age"}
name=data["name"]
Enter fullscreen mode Exit fullscreen mode

wrong

data = {"name", "age"}
name=data[1]
Enter fullscreen mode Exit fullscreen mode

wrong

data = {"name", "age"}
for keys in data.keys():
Enter fullscreen mode Exit fullscreen mode

wrong

data = {"name", "age"}
for keys in data.items():
Enter fullscreen mode Exit fullscreen mode

wrong

Image description

input_string = "programming"
my_list = "python"
character_count = {}

# Check if len(my_list) is greater than 0 before accessing elements
if len(my_list) > 0:
    # Iterate over the characters and indices using enumerate
    for index, char in enumerate(input_string):

        print(my_list[index])
Enter fullscreen mode Exit fullscreen mode

correct

input_string = "programming"
my_list = "python"
character_count = {}

# Check if len(my_list) is greater than 0 before accessing elements
if len(my_list) > 0:
    # Iterate over the characters and indices using enumerate
    for index, char in enumerate(input_string):
        if index < len(my_list): 
         print(my_list[index])
Enter fullscreen mode Exit fullscreen mode
input_string = "programming"
my_list = "python"
character_count = {}

# Check if len(my_list) is greater than 0 before accessing elements
if len(my_list) > 0:
    # Iterate over the characters and indices using enumerate
    for index, char in enumerate(input_string):
        my_list_char = my_list[index % len(my_list)]
        print(my_list_char)
Enter fullscreen mode Exit fullscreen mode

wrong

two ways to find sum of dictionary

1st way

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90

sum_of_values = 0
for value in data.values():
    sum_of_values += value

print(sum_of_values)
Enter fullscreen mode Exit fullscreen mode

2nd way

sum(data.values())
Enter fullscreen mode Exit fullscreen mode

two ways to find length of dictionary

1st way

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
len=0
sum_of_values = 0
for key in data.keys():
    len += 1
print(len)
Enter fullscreen mode Exit fullscreen mode

2nd way

my_dict = {"apple": 70, "banana": 33, "mango": 90}
dict_length = len(my_dict)
Enter fullscreen mode Exit fullscreen mode

3 ways to find avg of dictionary

1st way

data = {"apple": 70, "banana": 33}
name = data["apple"]
data["mango"] = 90
len=0
sum_of_values = 0
avg=0
for key,values in data.items():
    len += 1
    sum_of_values +=values
avg=sum_of_values/len  
print(avg)
Enter fullscreen mode Exit fullscreen mode

2nd way

my_dict = {"apple": 70, "banana": 33, "mango": 90}

total = 0
count = 0

for value in my_dict.values():
    total += value
    count += 1

if count > 0:
    average = total / count
    print("Average value:", average)
else:
    print("The dictionary is empty.")
Enter fullscreen mode Exit fullscreen mode

3rd way

my_dict = {"apple": 70, "banana": 33, "mango": 90}

if len(my_dict) > 0:
    average = sum(my_dict.values()) / len(my_dict)
    print("Average value:", average)
else:
    print("The dictionary is empty.")
Enter fullscreen mode Exit fullscreen mode
# Online Python - IDE, Editor, Compiler, Interpreter
listing={"apple":80,"banana":20,"peru":35,"mango":28}
dict_item={}
length=0
sums=0
avg=0
for index in range(len(listing.keys())):
    pass

avg=sum(listing.values())/(index+1) 
print(avg)
Enter fullscreen mode Exit fullscreen mode

find avg of all values if dictionary using list comprehension

# Online Python - IDE, Editor, Compiler, Interpreter
listing={"apple":80,"banana":20,"peru":35,"mango":28}
dict_item={}
length=0
sums=0
avg=0
listsum=[value for key,value in listing.items()]
print(listsum) 
listlen=[1 for key in listing.keys()]
print(listlen) 
sums=sum(listsum)
print(sums) 
length=len(listlen)
print(length) 
avg=sums/length
print(avg) 
Enter fullscreen mode Exit fullscreen mode

output

Image description

** 2 ways max data**

words_list = [20,60,70,80]
maxdatas=0
for max_data in words_list:
    if maxdatas>max_data:
       maxdatas=maxdatas
    else:
         maxdatas=max_data
print(maxdatas)  
Enter fullscreen mode Exit fullscreen mode
max(list)
Enter fullscreen mode Exit fullscreen mode

how to find index of particular value of list

list[3]
Enter fullscreen mode Exit fullscreen mode
listing = [6, 9, 6, 0, 45, 8]
data = ["good is located in " + str(index) if value == 8 else "bad" for index, value in enumerate(listing)]
print(data)
Enter fullscreen mode Exit fullscreen mode

Image description

Cheatsheet

data.update(update)//update specfic value in dictionary
Dict['Emp_ages'] = 20 //add new value in dictionary
for key in data.keys(): or for group in data.keys(): //print all key in dictionary
for value in data.values()://print all value in dictionary
for key,value in data.items(): or for group,ein data.items(): // print both
if char in characters_to_remove: // for list
if char not in characters_to_remove: // for list
if char not in vowels// for string
if length in word_length_dict: // for dictionary
empty_string += new_char1

for index in range(len(data))://iterating with only index in range
    if data[index] % 2 == 0:
Enter fullscreen mode Exit fullscreen mode

original_string = original_string.replace(char, "")
for index, char in enumerate(input_string): // map char to corresponding list
for char, item in zip(input_string, my_list):

for char, item in character_count.items():
    print(f"Character '{char}' is for {item}.")
Enter fullscreen mode Exit fullscreen mode

character_count[char] +=1

length = len(word)

word_length_dict[length] = [word]

word_length_dict[length].append(word)

dict(sorted(my_dict.items(), key=lambda item: item[1]))

sorted_dict = dict(sorted(my_dict.items(), key=itemgetter(1)))

max_value = max(my_dict.values())

average_value = sum(my_dict.values()) / len(my_dict)
del contact_dict[key_to_remove]

contact_email = contacts_dict.get(name_to_lookup, "Contact not found")
print("Task 10 - Email for '{}':", contact_email)
Enter fullscreen mode Exit fullscreen mode
my_list = [8, 9, 7, 9, 56]
new_sum = sum(my_list)
Enter fullscreen mode Exit fullscreen mode
my_list = [8, 9, 7, 9, 56]
len= len(my_list)
Enter fullscreen mode Exit fullscreen mode

my_list = my_list + [new_data] // add new data in list

my_list = [1, 2, 3, 4, 5] // add new data in list
new_data = 6
my_list.append(new_data)
Enter fullscreen mode Exit fullscreen mode

dict["mango"]=90 // add new key value pair in dictionary

new_movie = {"director": "Director3", "genre": "Genre3"}
movies_dict["Movie3"] = new_movie  // add new key value pair in dictionary
Enter fullscreen mode Exit fullscreen mode

if seconlargestd < newdata < maxdata //second largest

merged_dict = {**dict1, **dict2, **dict3}

top_rated_songs = [title for title, rating in song_ratings.items() if rating == 5]

merged_list = list(set(list1 + list2))

strings_list = ["Hello", "World", "!"] // u can join particular string based on condition while iterating in loop
concatenated_string = ' '.join(strings_list)

full_urls = ['https://www.icc-cricket.com' + url for url in url_list] //how to concatenate

my_list.insert(index_to_insert, value_to_add)
my_list.insert(3, value_to_add)
Enter fullscreen mode Exit fullscreen mode

for index, text in enumerate(list): //Find Particular element index

subset = my_list[::2] // print even no

reversed_list = my_list[::-1]

subset = my_list[:3] # Get elements at index 0, 1, and 2 ([1, 2, 3])
subset = my_list[2:] # Get elements from index 2 to the end ([3, 4, 5])

subset = my_list[1:4] # Get elements at index 1, 2, and 3 ([2, 3, 4])

key_list = list(data.keys())

for key in data.keys():
    list.append(key)
Enter fullscreen mode Exit fullscreen mode

value_list = list(data.values())

for value in data.values():
    list.append(value)
Enter fullscreen mode Exit fullscreen mode

index = my_list.index(value_to_find) // how to find index of list

Summary

put colon not semicolon after for ,def ,if,else
after print or declaration of variable not put semicolon
indention of for and if
indention of if and else
indention for,if and data or print
Indention between for,if and local print global print
indention between for,if,else,print
indention between for,if,else,pass,print
always iterate in string,list,dictionary,tuple not single variable of list
How to add new char in empty string or exisiting string
print in new line or in list observe
How to add new char in empty string or exisiting string without for loop or inside for loop
Indention error b/w double for block
dont put gap b/w + and = operator
iterate over the indices and then access the elements whenever you use range
whenever string is in dictionary to access its value use double quotes
print key and value by comma or colon
not concatenate string with integer while doing calculation of sum of all dictionary value
RuntimeError: dictionary changed size during iteration
Declaration of empty datatype to create or append to create new like list,dictionary,string,integer,list of dictionary,dictionary of dictionary
Mapping char to corresponding item in list using zip
difference between char_count[item]=char or char_count[item]=[char] and word_count[length].append(word) inside for loop
how to search particular value based on key
two ways to find sum,length of value in list
3 ways to find avg of value in list
two way to access if dictionary contain only keys
two ways to find sum,len of dictionary
3ways to find avg of dictionary
2 ways to find max data in list
find second largest data
how to convert string to list

QUESTION

how to access list value or string value using index
how to access value from list of dictionary
difference between enumerate and zip method
.How to add new char in empty string or existing string
.How to Mapping char to corresponding item in list and dictionary OR how to convert list to dictionary
how to convert dictionary to list
how to search particular value based on key
how to find second largest data
how to convert dictionary keys or value in list
how to combine two list
how to reverse list
how to get specific range of element from list
how to get last 3 element of list
how to get skip fist element from list
how to combine dictionary
how to concatenate string in each element of list
how to update specific value in dictionary
how to find index of particular value of list or string
how to iterate index of list
how to string to list
Solution

my_list[index]

synonyms = {"quick": ["fast", "swift", "speedy"]}
list(synonyms.keys())

zip method iterates over element pairs and contain two parameter argument while enumerate iterates over element and index and contain one parameter argument of list

empty_string += new_char1

using enumerate or zip
using list comrehension or append while iterating dictionary

movies_dict["Movie3"]

if seconlargestd < newdata < maxdata //second largest

key_list = list(data.keys()) or list.append(key) inside for loop

merged_list = list(set(list1 + list2)) or listnew=list1 + list2

reversed_list = my_list[::-1]

subset = my_list[1:4]

subset = my_list[:3]

subset = my_list[1:]

merged_dict = {**dict1, **dict2, **dict3}

full_urls = ['https://www.icc-cricket.com' + url for url in url_list]

data.update(update)

list[3] or [data for data in list if 5==data] or using enumerte

for index, char in enumerate(input_string):
     character_count[char] = my_list[index]
#printing
for index, char in enumerate(input_string):
     my_list_char = my_list[index % len(my_list)]
     print(my_list[index])
Enter fullscreen mode Exit fullscreen mode

data= ["good is located in " + str(index) if value == 8 else "bad" for index, value in enumerate(listing)]
using enumerate
list(string) or append inside for loop

Top comments (0)