Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Reverse
- num = int(input("Enter a number: "))
- reversed_num = 0
- while num > 0:
- digit = num % 10
- reversed_num = (reversed_num * 10) + digit
- num = num // 10
- print(f"The reversed number: {reversed_num}")
- #fibonacchi
- num_terms = int(input("Enter the number of terms for the Fibonacci series: "))
- if num_terms <= 0:
- print("Invalid input. Please enter a positive integer.")
- else:
- fib_series = [0, 1]
- while len(fib_series) < num_terms:
- fib_series.append(fib_series[-1] + fib_series[-2])
- sum_fib_series = sum(fib_series)
- print(f"The sum of the first {num_terms} terms in the Fibonacci series is: {sum_fib_series}")
- #armstrong
- num = int(input("Enter a number: "))
- original_num = num
- num_digits = len(str(num))
- sum_of_digits = 0
- while num > 0:
- digit = num % 10
- sum_of_digits += digit ** num_digits
- num = num // 10
- if original_num == sum_of_digits:
- print(f"{original_num} is an Armstrong number.")
- else:
- print(f"{original_num} is not an Armstrong number.")
- #positive negative sum
- sum_positive = 0
- sum_negative = 0
- for i in range(10):
- num = float(input(f"Enter number {i + 1}: "))
- if num > 0:
- sum_positive += num
- elif num < 0:
- sum_negative += num
- print(f"Sum of positive numbers: {sum_positive}")
- print(f"Sum of negative numbers: {sum_negative}")
- #palindrome
- num = int(input("Enter a number: "))
- original_num = num
- reversed_num = 0
- while num > 0:
- digit = num % 10
- reversed_num = (reversed_num * 10) + digit
- num = num // 10
- if original_num == reversed_num:
- print(f"{original_num} is a palindrome.")
- else:
- print(f"{original_num} is not a palindrome.")
- *
- * *
- * * *
- * * * *
- * * * * *
- rows = 5
- for i in range(0, rows):
- for j in range(0, i + 1):
- print("*", end=' ')
- print()
- 1
- 2 2
- 3 3 3
- 4 4 4 4
- 5 5 5 5 5
- rows = 6
- for i in range(rows):
- for j in range(i):
- print(i, end=' ')
- print('')
- 1
- 1 2
- 1 2 3
- 1 2 3 4
- 1 2 3 4 5
- rows = 5
- for i in range(1, rows + 1):
- for j in range(1, i + 1):
- print(j, end=' ')
- print('')
- 1
- 2 3
- 4 5 6
- 7 8 9 10
- 11 12 13 14 15
- rows = 5
- counter = 1
- for i in range(1, rows + 1):
- for j in range(1, i + 1):
- print(counter, end=' ')
- counter += 1
- print('')
- *
- * *
- * * *
- * * * *
- * * * * *
- size = 5
- m = (2 * size) - 2
- for i in range(0, size):
- for j in range(0, m):
- print(end=" ")
- m = m - 1
- for j in range(0, i + 1):
- print("* ", end=' ')
- print(" ")
- ''' OR
- n = 5
- for i in range(n):
- print(' '*(n-i-1) + '* ' * (i))
- print()
- '''
- * * * * *
- * * * *
- * * *
- * *
- *
- size = 5
- m = 0
- for i in range(size, 0, -1):
- for j in range(0, m):
- print(end=" ")
- m = m + 1
- for j in range(0, i):
- print("* ", end=' ')
- print(" ")
- ''' OR
- n = 5
- for i in range(n-1,-1,-1):
- print(' ' * (n - i - 1) + '* ' * (i))
- '''
- *
- * *
- * * *
- * * * *
- * * *
- * *
- *
- rows = 3
- k = 2 * rows - 2
- for i in range(0, rows):
- for j in range(0, k):
- print(end=" ")
- k = k - 1
- for j in range(0, i + 1):
- print("* ", end="")
- print("")
- k = rows - 2
- for i in range(rows, -1, -1):
- for j in range(k, 0, -1):
- print(end=" ")
- k = k + 1
- for j in range(0, i + 1):
- print("* ", end="")
- print("")
- '''OR
- n = 3
- for i in range(n):
- print(' '*(n-i-1) + '*' * (2*i+1))
- for i in range(n-2,-1,-1):
- print(' ' * (n - i - 1) + '*' * (2 * i + 1))'''
- #calculator
- def addition(num1, num2):
- num1 += num2
- return num1
- def subtraction(num1, num2):
- num1 -= num2
- return num1
- def mul(num1, num2):
- num1 *= num2
- return num1
- def division(num1, num2):
- if num2 != 0:
- num1 /= num2
- return num1
- else:
- return "Cannot divide by zero"
- def module(num1, num2):
- if num2 != 0:
- num1 %= num2
- return num1
- else:
- return "Cannot perform modulus with zero"
- def default(num1, num2):
- return "Incorrect day"
- switcher = {
- 1: addition,
- 2: subtraction,
- 3: mul,
- 4: division,
- 5: module
- }
- def switch(operation):
- num1 = float(input("Enter the first number: "))
- num2 = float(input("Enter the second number: "))
- return switcher.get(operation, default)(num1, num2)
- print('''You can perform the following operations:
- 1. **Addition**
- 2. **Subtraction**
- 3. **Multiplication**
- 4. **Division**
- 5. **Modulus (Remainder)''')
- # Take input from the user
- choice = int(input("Select an operation from 1 to 5: "))
- print(switch(choice))
- #Fibonacchi using recursion
- def fibonacci(n):
- if n <= 0:
- return "Please enter a positive integer"
- elif n == 1:
- return [0]
- elif n == 2:
- return [0, 1]
- else:
- fib_series = fibonacci(n - 1)
- fib_series.append(fib_series[-1] + fib_series[-2])
- return fib_series
- n = int(input("Enter the value of 'n' to print Fibonacci series up to n: "))
- result = fibonacci(n)
- print(f"Fibonacci series up to {n}: {result}")
- #GCD using recurtion
- def gcd_recursive(a, b):
- if b == 0:
- return a
- else:
- return gcd_recursive(b, a % b)
- # Take input from the user
- num1 = int(input("Enter the first number: "))
- num2 = int(input("Enter the second number: "))
- result = gcd_recursive(num1, num2)
- print(f"The GCD of {num1} and {num2} is: {result}")
- # Wap to print sum of list
- l1 = [12+13+14+15+56]
- sum = 0
- for i in l1:
- sum += i
- print(sum
- #output
- 110
- #Wap to print mal element
- ls=[]
- print("Enter Elements in array")
- for i in range(5):
- el=int(input())
- ls.append(el)
- maxel=ls[0]
- mi=0
- for i in range(1,len(ls)):
- if ls[i]>maxel:
- maxel=ls[i]
- mi = i
- print("Max element is: ",maxel)
- #output
- Enter Elements in array
- 13
- 67
- 34
- 99
- 12
- Max element is: 99
- #wap to print common elements
- def compare_lists(list1, list2):
- common_elements = set(list1) & set(list2)
- return list(common_elements)
- list1_input = input("Enter elements of the first list separated by spaces: ")
- list1 = list(map(str, list1_input.split()))
- list2_input = input("Enter elements of the second list separated by spaces: ")
- list2 = list(map(str, list2_input.split()))
- common_elements = compare_lists(list1, list2)
- if common_elements:
- print("Common elements: ", common_elements)
- else:
- print("No common elements found.")
- #output
- Enter elements of the first list separated by spaces: 12 13 45 67 89
- Enter elements of the second list separated by spaces: 12 45 67 89
- Common elements: ['12', '45', '67', '89']
- #Wap to remove even numbers
- def remove_even_numbers(input_list):
- return [num for num in input_list if int(num) % 2 != 0]
- user_input = input("Enter a list of numbers separated by spaces: ")
- numbers_list = user_input.split()
- filtered_list = remove_even_numbers(numbers_list)
- print("List after removing even numbers:", filtered_list)
- #output
- Enter a list of numbers separated by spaces: 12 34 56 77 43 31
- List after removing even numbers: ['77', '43', '31']
- #Wap to print number of occurance
- def count_occurrences(array, target_element):
- return array.count(target_element)
- user_input = input("Enter a list of numbers separated by spaces: ")
- numbers_list = user_input.split()
- target_element = input("Enter the element to count: ")
- occurrences = count_occurrences(numbers_list, target_element)
- print(f"The number of occurrences of {target_element} in the list is: {occurrences}")
- #output
- Enter a list of numbers separated by spaces: 12 33 33 45 67 54
- Enter the element to count: 33
- The number of occurrences of 33 in the list is: 2
- #accept and print matrix
- matrix = []
- for i in range(3):
- row = []
- for j in range(3):
- row.append(int(input(f"Enter element at position ({i+1}, {j+1}): ")))
- matrix.append(row)
- print("Entered 3x3 matrix:")
- for row in matrix:
- print(row)
- output:
- Enter element at position (1, 1): 1
- Enter element at position (1, 2): 2
- Enter element at position (1, 3): 3
- Enter element at position (2, 1): 4
- Enter element at position (2, 2): 5
- Enter element at position (2, 3): 6
- Enter element at position (3, 1): 7
- Enter element at position (3, 2): 8
- Enter element at position (3, 3): 9
- Entered 3x3 matrix:
- [1, 2, 3]
- [4, 5, 6]
- [7, 8, 9]
- #accept matrix and element sum
- matrix = []
- a=0
- sum=0
- for i in range(3):
- row = []
- for j in range(3):
- a=int(input(f"Enter element at position ({i+1}, {j+1}): "))
- row.append(a)
- sum+=a
- matrix.append(row)
- print("Entered 3x3 matrix:")
- for row in matrix:
- print(row)
- print("Sum = ",sum)
- Output:
- Enter element at position (1, 1): 1
- Enter element at position (1, 2): 2
- Enter element at position (1, 3): 3
- Enter element at position (2, 1): 4
- Enter element at position (2, 2): 5
- Enter element at position (2, 3): 6
- Enter element at position (3, 1): 7
- Enter element at position (3, 2): 8
- Enter element at position (3, 3): 9
- Entered 3x3 matrix:
- [1, 2, 3]
- [4, 5, 6]
- [7, 8, 9]
- Sum = 45
- #Accept matrix and trace
- matrix = []
- for i in range(3):
- row = []
- for j in range(3):
- element = int(input(f"Enter element at position ({i+1}, {j+1}): "))
- row.append(element)
- matrix.append(row)
- print("Entered 3x3 matrix:")
- for row in matrix:
- print(row)
- trace = 0
- for i in range(3):
- trace += matrix[i][i]
- print(f"Trace of the matrix: {trace}")
- Output:
- Enter element at position (1, 1): 1
- Enter element at position (1, 2): 2
- Enter element at position (1, 3): 3
- Enter element at position (2, 1): 4
- Enter element at position (2, 2): 5
- Enter element at position (2, 3): 6
- Enter element at position (3, 1): 7
- Enter element at position (3, 2): 8
- Enter element at position (3, 3): 9
- Entered 3x3 matrix:
- [1, 2, 3]
- [4, 5, 6]
- [7, 8, 9]
- Trace of the matrix: 15
- #Matrix multiplication
- import numpy as np
- matrix1 = []
- for i in range(3):
- row = []
- for j in range(3):
- element = int(input(f"Enter element for matrix1 at position ({i+1}, {j+1}): "))
- row.append(element)
- matrix1.append(row)
- matrix2 = []
- for i in range(3):
- row = []
- for j in range(3):
- element = int(input(f"Enter element for matrix2 at position ({i+1}, {j+1}): "))
- row.append(element)
- matrix2.append(row)
- print("Entered 3x3 matrix 1:")
- for row in matrix1:
- print(row)
- print("\nEntered 3x3 matrix 2:")
- for row in matrix2:
- print(row)
- array1 = np.array(matrix1)
- array2 = np.array(matrix2)
- result_array = np.dot(array1, array2)
- print("\nResult of matrix multiplication:")
- print(result_array)
- Output:
- Enter element for matrix1 at position (1, 1): 1
- Enter element for matrix1 at position (1, 2): 2
- Enter element for matrix1 at position (1, 3): 3
- Enter element for matrix1 at position (2, 1): 4
- Enter element for matrix1 at position (2, 2): 5
- Enter element for matrix1 at position (2, 3): 6
- Enter element for matrix1 at position (3, 1): 7
- Enter element for matrix1 at position (3, 2): 8
- Enter element for matrix1 at position (3, 3): 9
- Enter element for matrix2 at position (1, 1): 1
- Enter element for matrix2 at position (1, 2): 10
- Enter element for matrix2 at position (1, 3): 11
- Enter element for matrix2 at position (2, 1): 12
- Enter element for matrix2 at position (2, 2): 13
- Enter element for matrix2 at position (2, 3): 14
- Enter element for matrix2 at position (3, 1): 15
- Enter element for matrix2 at position (3, 2): 16
- Enter element for matrix2 at position (3, 3): 17
- Entered 3x3 matrix 1:
- [1, 2, 3]
- [4, 5, 6]
- [7, 8, 9]
- Entered 3x3 matrix 2:
- [1, 10, 11]
- [12, 13, 14]
- [15, 16, 17]
- Result of matrix multiplication:
- [[ 70 84 90]
- [154 201 216]
- [238 318 342]]
- #Count vowels, consonants and blanks
- def count_vowels_consonants_blanks(string):
- vowels = 'aeiouAEIOU'
- consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
- blanks = ' '
- vowel_count = 0
- consonant_count = 0
- blank_count = 0
- for char in string:
- if char in vowels:
- vowel_count += 1
- elif char not in consonants:
- consonant_count += 1
- elif char in blanks:
- blank_count += 1
- return vowel_count, consonant_count, blank_count
- input_string = input("Enter a string: ")
- vowels, consonants, blanks = count_vowels_consonants_blanks(input_string)
- print("Vowels:", vowels)
- print("Consonants:", consonants)
- print("Blanks:", blanks)
- #Output:
- Enter a string: Arijit is my name
- Vowels: 6
- Consonants: 8
- Blanks: 3
- #find substring in a string
- def find_substring(string, substring):
- index = string.find(substring)
- if index != -1:
- print(f"'{substring}' found at index {index} using find() method.")
- else:
- print(f"'{substring}' not found using find() method.")
- input_string = input("Enter the main string: ")
- input_substring = input("Enter the substring to find: ")
- find_substring(input_string, input_substring)
- #Output:
- Enter the main string: i live in India
- Enter the substring to find: India
- 'India' found at index 10 using find() method.
- #print reverse and check palindrome
- def is_palindrome(string):
- reversed_string = string[::-1]
- if string == reversed_string:
- return True, reversed_string
- else:
- return False, reversed_string
- input_string = input("Enter a string: ")
- check, reversed_string = is_palindrome(input_string)
- print("Original string:", input_string)
- print("Reversed string:", reversed_string)
- if check:
- print("The string is a palindrome.")
- else:
- print("The string is not a palindrome.")
- #Output:
- Enter a string: malayalam
- Original string: malayalam
- Reversed string: malayalam
- The string is a palindrome.
- #Print pattern
- word = "INDIA"
- for i in range(len(word), 0, -1):
- print(word[:i])
- #Ouput:
- INDIA
- INDI
- IND
- IN
- I
- def tuple_length(tup):
- return len(tup)
- my_tuple = (1, 2, 3, 4, 5)
- print("Length of the tuple:", tuple_length(my_tuple))
- Output:
- Length of the tuple: 5
- def tuple_to_string(tup):
- return ''.join(tup)
- my_tuple = ('Hello', ' ', 'world', '!')
- result = tuple_to_string(my_tuple)
- print("Converted string:", result)
- Output:
- Converted string: Hello world!
- def common_elements(tup1, tup2):
- common = tuple(x for x in tup1 if x in tup2)
- return common
- tuple1 = (1, 2, 3, 4, 5)
- tuple2 = (4, 5, 6, 7, 8)
- result = common_elements(tuple1, tuple2)
- print("Common elements:", result)
- Output:
- Common elements: (4, 5)
- def merge_tuples(tup1, tup2):
- merged_list = list(tup1)
- for item in tup2:
- if item not in merged_list:
- merged_list.append(item)
- merged_tuple = tuple(merged_list)
- return merged_tuple
- tuple1 = (1, 2, 3, 4, 5)
- tuple2 = (4, 5, 6, 7, 8)
- result = merge_tuples(tuple1, tuple2)
- print("Merged tuple without duplicates:", result)
- Output:
- Merged tuple without duplicates: (1, 2, 3, 4, 5, 6, 7, 8)
- def even_odd_numbers(tup):
- even_numbers = tuple(num for num in tup if num % 2 == 0)
- odd_numbers = tuple(num for num in tup if num % 2 != 0)
- return even_numbers, odd_numbers
- my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
- even, odd = even_odd_numbers(my_tuple)
- print("Even numbers:", even)
- print("Odd numbers:", odd)
- Output:
- Even numbers: (2, 4, 6, 8)
- Odd numbers: (1, 3, 5, 7, 9)
- def tuple_product(tup):
- product = 1
- for num in tup:
- product *= num
- return product
- my_tuple = (1, 2, 3, 4, 5)
- result = tuple_product(my_tuple)
- print("Product of all elements in the tuple:", result)
- Output:
- Product of all elements in the tuple: 120
- emails = tuple()
- username = tuple()
- domainname = tuple()
- n = int(input("How many email ids you want to enter?: "))
- for i in range(0, n):
- emid = input("> ")
- emails = emails + (emid,)
- spl = emid.split("@")
- username = username + (spl[0],)
- domainname = domainname + (spl[1],)
- print("\nThe email ids in the tuple are:")
- print(emails)
- print("\nThe username in the email ids are:")
- print(username)
- print("\nThe domain name in the email ids are:")
- print(domainname)
- Output:
- How many email ids you want to enter?: 2
- > arijit@gmail.com
- > abir@outlook.com
- The email ids in the tuple are:
- ('arijit@gmail.com', 'abir@outlook.com')
- The username in the email ids are:
- ('arijit', 'abir')
- The domain name in the email ids are:
- ('gmail.com', 'outlook.com')
- #Q1. python program to check if a string starts with the and end with spain use regex
- import re
- def check_string(input_string):
- pattern = r'^the.*spain$'
- if re.match(pattern, input_string, re.IGNORECASE):
- return True
- else:
- return False
- test_string1 = input("Enter string: ")
- print(check_string(test_string1))
- #output:
- Enter string: the spain
- True
- Enter string: the spain not
- False
- #Q. program to find all lowercase charcters aplhabetically between a and m, use regex
- import re
- def find_lower_chars(input_string):
- pattern = r'[a-m]'
- result = re.findall(pattern, input_string)
- return result
- user_input = input("Enter a string: ")
- lowercase_chars = find_lower_chars(user_input)
- print("Lowercase characters between 'a' and 'm':", lowercase_chars)
- #output:
- Enter a string: The quick brown fox jumps over the lazy dog
- Lowercase characters between 'a' and 'm': ['h', 'e', 'i', 'c', 'k', 'b', 'f', 'j', 'm', 'e', 'h', 'e', 'l', 'a', 'd', 'g']
- #Q. program to search for the first white space character in the string
- import re
- txt = "The rain in Spain"
- x = re.search("\s", txt)
- print("The first white-space character is located in position:", x.start())
- #Output:
- The first white-space character is located in position: 3
- #Q. program to split at each whitespace character using regex
- import re
- def split_at_whitespace(input_string):
- return re.split(r'\s+', input_string)
- user_input = input("Enter a string: ")
- result = split_at_whitespace(user_input)
- print("Split at each whitespace character:", result)
- #Output:
- Enter a string: This is a demo input.
- Split at each whitespace character: ['This', 'is', 'a', 'demo', 'input.']
- #Q. replace every white space character with the number nine
- import re
- def replace_whitespace_with_nine(input_string):
- return re.sub(r'\s', '9', input_string)
- user_input = input("Enter a string: ")
- result = replace_whitespace_with_nine(user_input)
- print("String with every whitespace character replaced with '9':", result)
- #Output:
- Enter a string: This is a demo input
- String with every whitespace character replaced with '9': This9is9a9demo9inputp
- #Q: check if email valid or not:
- import re
- def validate_email(email):
- pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
- regex = re.compile(pattern)
- return bool(regex.match(email))
- user_email = input("Enter your email address: ")
- if validate_email(user_email):
- print("Valid email address!")
- else:
- print("Invalid email address. Please enter a valid email.")
- #Output:
- Enter your email address: arijit@gmail.com
- Valid email address!
- Enter your email address: arijit@gmail
- Invalid email address. Please enter a valid email.
- #Q1. python program to check if a string starts with the and end with spain use regex
- import re
- def check_string(input_string):
- pattern = r'^the.*spain$'
- if re.match(pattern, input_string, re.IGNORECASE):
- return True
- else:
- return False
- test_string1 = input("Enter string: ")
- print(check_string(test_string1))
- #output:
- Enter string: the spain
- True
- Enter string: the spain not
- False
- #Q. program to find all lowercase charcters aplhabetically between a and m, use regex
- import re
- def find_lower_chars(input_string):
- pattern = r'[a-m]'
- result = re.findall(pattern, input_string)
- return result
- user_input = input("Enter a string: ")
- lowercase_chars = find_lower_chars(user_input)
- print("Lowercase characters between 'a' and 'm':", lowercase_chars)
- #output:
- Enter a string: The quick brown fox jumps over the lazy dog
- Lowercase characters between 'a' and 'm': ['h', 'e', 'i', 'c', 'k', 'b', 'f', 'j', 'm', 'e', 'h', 'e', 'l', 'a', 'd', 'g']
- #Q. program to search for the first white space character in the string
- import re
- txt = "The rain in Spain"
- x = re.search("\s", txt)
- print("The first white-space character is located in position:", x.start())
- #Output:
- The first white-space character is located in position: 3
- #Q. program to split at each whitespace character using regex
- import re
- def split_at_whitespace(input_string):
- return re.split(r'\s+', input_string)
- user_input = input("Enter a string: ")
- result = split_at_whitespace(user_input)
- print("Split at each whitespace character:", result)
- #Output:
- Enter a string: This is a demo input.
- Split at each whitespace character: ['This', 'is', 'a', 'demo', 'input.']
- #Q. replace every white space character with the number nine
- import re
- def replace_whitespace_with_nine(input_string):
- return re.sub(r'\s', '9', input_string)
- user_input = input("Enter a string: ")
- result = replace_whitespace_with_nine(user_input)
- print("String with every whitespace character replaced with '9':", result)
- #Output:
- Enter a string: This is a demo input
- String with every whitespace character replaced with '9': This9is9a9demo9inputp
- #Q: check if email valid or not:
- import re
- def validate_email(email):
- pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
- regex = re.compile(pattern)
- return bool(regex.match(email))
- user_email = input("Enter your email address: ")
- if validate_email(user_email):
- print("Valid email address!")
- else:
- print("Invalid email address. Please enter a valid email.")
- #Output:
- Enter your email address: arijit@gmail.com
- Valid email address!
- Enter your email address: arijit@gmail
- Invalid email address. Please enter a valid email.
- #Bubble sort
- def bubble_sort(arr):
- n = len(arr)
- for i in range(n):
- for j in range(0, n-i-1):
- if arr[j] > arr[j+1]:
- arr[j], arr[j+1] = arr[j+1], arr[j]
- arr = []
- size = int(input("Enter the size of the array: "))
- print("Enter the elements of the array:")
- for _ in range(size):
- element = int(input())
- arr.append(element)
- bubble_sort(arr)
- print("Sorted array is:", arr)
- # Creating a dictionary with key-value pairs using dict() function taking user input
- my_dict = {}
- num_pairs = int(input("Enter the number of key-value pairs: "))
- for i in range(num_pairs):
- key = input("Enter key {}: ".format(i+1))
- value = input("Enter value {}: ".format(i+1))
- my_dict[key] = value
- print("Dictionary created:", my_dict)
- #output
- Enter the number of key-value pairs: 2
- Enter key 1: hello
- Enter value 1: 2
- Enter key 2: word
- Enter value 2: 2
- Dictionary created: {'hello': '2', 'word': '2'}
- #WAP in python to insert three elements and Pop 1 element from a Dictionary.
- my_dict = {}
- my_dict['apple'] = 10
- my_dict['banana'] = 20
- my_dict['orange'] = 30
- print("Original dictionary:", my_dict)
- popped_item = my_dict.popitem()
- print("Popped item:", popped_item)
- print("Dictionary after popping one element:", my_dict)
- #output:
- Original dictionary: {'apple': 10, 'banana': 20, 'orange': 30}
- Popped item: ('orange', 30)
- Dictionary after popping one element: {'apple': 10, 'banana': 20}
- #WAP in python to find sum of all items in a Dictionary
- my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
- total_sum = sum(my_dict.values())
- print("Sum of all items in the dictionary:", total_sum)
- #output:
- Sum of all items in the dictionary: 100
- # WAP in python update the value of a dictionary in Python if the particular key exists. If the key is not
- #present in the dictionary, we will simply print that the key does not exist
- my_dict = {'a': 10, 'b': 20, 'c': 30}
- key_to_update = input("Enter the key to update: ")
- new_value = input("Enter the new value: ")
- if key_to_update in my_dict:
- my_dict[key_to_update] = new_value
- else:
- print("The key does not exist")
- print("Updated dictionary:", my_dict)
- #output:
- Enter the key to update: a
- Enter the new value: 6
- Updated dictionary: {'a': '6', 'b': 20, 'c': 30}
- #Write a program to get the maximum and minimum value of dictionary
- my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 5}
- max_value = max(my_dict.values())
- min_value = min(my_dict.values())
- print("Maximum value in the dictionary:", max_value)
- print("Minimum value in the dictionary:", min_value)
- #output
- Maximum value in the dictionary: 30
- Minimum value in the dictionary: 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement