Page 72 - Touhpad Ai
P. 72

Operations on Dictionary

              A dictionary is a collection of key-value pairs. Dictionaries are defined by enclosing elements in curly braces { }.
              Creating a Dictionary
              A dictionary can be created by enclosing key-value pairs in curly braces {}, with each pair separated by commas. Within
              each pair, the key and value are divided by a colon “:”
                 # Creating a dictionary
                 car = {
                     "make": "Toyota",
                     "model": "Camry",
                     "year": 2021,
                     "colour": "Blue"
                 }
              You can access the values in a dictionary by using the keys as shown:
                 print(car) # Output: {'make': 'Toyota', 'model': 'Camry', 'year': 2021, 'colour':
                 'Blue'}
                 print(car["make"])  # Output: Toyota
                 print(car["year"])   # Output: 2021

              Mutability
              In dictionaries, keys are immutable whereas values are mutable. You can change the values using the respective keys:

                 car["colour"]="Grey"
                 print(car)   #Ouput: {'make': 'Toyota', 'model': 'Camry', 'year': 2021, 'colour': 'Grey'}
              You can also add key-value pairs in an existing dictionary:
                 car["mileage"] = 15000
                 print (car)  #Ouput: {'make': 'Toyota', 'model': 'Camry', 'year': 2021, 'colour':
                 'Grey', 'mileage': 15000}

              Control Statements
              Control statements in programming languages are essential tools that allow developers to dictate the flow of execution
              within their code. Depending on how the statements in a program will be executed, the flow of control in a program can
              be broadly classified into three types:
              Sequence Statements
              Conditional Statements
              Iterative Statements
              Sequence Statement
              In Python, a sequence statement refers to a set of instructions that are executed in the order they appear. This is the most
              straightforward form of control flow.

                 Program 13: To demonstrate the concept of Sequence statement
                 # Perform an Addition
                 num1 = 10
                 num2 = 20
                 result = num1 + num2
                 # Display the result
                 print("The result of", num1, "+", num2, "is:", result)


                 70     Touchpad Artificial Intelligence - XI
   67   68   69   70   71   72   73   74   75   76   77