1 Write a Python program to calculate the length of a string
def string_length(str1):
count = 0
for char in str1:
count += 1
return count
print(string_length('stanley.edu.in'))
2 Write a Python program to sum all the items in a list.
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
3 Write a Python program to get the largest number from a list.
● def max_num_in_list( list ):
● max = list[ 0 ]
● for a in list:
● if a > max:
● max = a
● return max
● print(max_num_in_list([1, 2, -8, 0]))
Write a Python program to sort (ascending and descending) a dictionary by value
● import operator
● d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
● print('Original dictionary : ',d)
● sorted_d = sorted(d.items(), key=operator.itemgetter(0))
● print('Dictionary in ascending order by value : ',sorted_d)
● sorted_d = sorted(d.items(),
key=operator.itemgetter(0),reverse=True)
● print('Dictionary in descending order by value : ',sorted_d)
Write a Python program to add key to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30}
● d = {0:10, 1:20}
● print(d)
● d.update({2:30})
● print(d)
Write a Python program to check if a given key already exists in a dictionary.
● d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
● def is_key_present(x):
● if x in d:
● print('Key is present in the dictionary')
● else:
● print('Key is not present in the dictionary')
● is_key_present(5)
● is_key_present(9)
Write a Python program to check a list is empty or not.
● l = []
● if not l:
● print("List is empty")
Write a Python program to iterate over dictionaries using for loops.
● d = {'x': 10, 'y': 20, 'z': 30}
● for dict_key, dict_value in d.items():
● print(dict_key,'->',dict_value)
Write a Python program to count the number of characters (character frequency)
in a string.
Sample String : google.com'
Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}
● def char_frequency(str1):
● dict = {}
● for n in str1:
● keys = dict.keys()
● if n in keys:
● dict[n] += 1
● else:
● dict[n] = 1
● return dict
● print(char_frequency('google.com'))
Create an Empty Set in Python
# create an empty set
empty_set = set()
# create an empty dictionary
empty_dictionary = { }
# check data type of empty_set
print('Data type of empty_set:', type(empty_set))
# check data type of dictionary_set
print('Data type of empty_dictionary:', type(empty_dictionary))
Add Items to a Set in Python
numbers = {21, 34, 54, 12}
print('Initial Set:',numbers)
# using add() method
numbers.add(32)
print('Updated Set:', numbers)