Page 525 - ComputerScience_Class_11
P. 525

Program 5: Write a program to count the frequency of each character in a string using a dictionary and a function.
                      Program 5.py

                  File  Edit  Format   Run    Options  Window     Help

                  def count_character_frequency(input_string):
                      frequency = {}
                      # Loop through each character in the string
                      for char in input_string:
                          if char in frequency:
                              frequency[char] += 1   # Increase count if character already exists
                          else:
                              frequency[char] = 1    # Add character with count 1 if it is not present
                      return frequency
                  text = "hello world"
                  # Call the function
                  char_frequency = count_character_frequency(text)
                  # Print the result
                  print("Character frequencies:", char_frequency)



                     Output

                  Character frequencies: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}



                 Program 6: Write a program to verify login details using a dictionary.
                     Program 6.py

                  File  Edit  Format   Run   Options   Window     Help

                  def verify_login(login_details, username, password):
                      if username in login_details:
                          if login_details[username] == password:
                              return "Login successful"
                          else:
                              return "Incorrect password"
                      else:
                          return "Username not found"
                  login_details = { 'yogesh101': 'password123', 'nitin2': 'securepass',
                                    'ritik123': 'mysecret', 'arjun': 'password321' }
                  username_input = input("Enter your username: ").lower()
                  password_input = input("Enter your password: ")
                  login_result = verify_login(login_details, username_input, password_input)
                  print(login_result)




                     Output

                  Enter your username: ritik123
                  Enter your password: mysecret
                  Login successful





                                                                              For Advance Learners: Functions in Python  523
   520   521   522   523   524   525   526   527   528   529   530