Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 137 - 2615_KEC
P. 137

    Program 5: A program to create a tuple that contains the same exam subjects

                         Program5.py
                      File  Edit  Format   Run    Options   Window    Help

                      exam_subjects_tuple = ("Math", "Science", "English", "History", "Computer")
                      print("Original Tuple:", exam_subjects_tuple)

                         Output

                      Original Tuple: ('Math', 'Science', 'English', 'History', 'Computer')

                     Let's try to change the English subject to Biology. Since tuples are immutable, this will give an error.

                     Program 6: A program to modify a tuple element.

                         Program6.py
                      File  Edit  Format   Run    Options   Window    Help

                      exam_subjects_tuple = ("Math", "Science", "English", "History", "Computer")
                      exam_subjects_tuple[2] = "Biology"  # Trying to change 'English' to 'Biology'

                         Output

                      Traceback (most recent call last):
                        File "C:/Users/ ", line 2, in <module>
                          exam_subjects_tuple[2] = "Biology"  # Trying to change 'English' to 'Biology'
                      TypeError: 'tuple' object does not support item assignment

                     SLICING THE TUPLE
                     Tuple slicing refers to accessing a part of a tuple using the slicing operator [:].

                     Program 7: To slice a Tuple of exam score.

                         Program7.py

                      File  Edit  Format   Run    Options   Window    Help

                      # Program to perform slicing on a tuple of exam scores
                      exam_scores = (85.5, 90.2, 78.9, 92.1, 88.6)
                      print("Exam Scores:", exam_scores)

                      # Slicing from index 1 to 4
                      print(exam_scores[1:4])  # Access elements from index 1 to 3

                                                                                                  Tuples and Dictionary  135

| 132 133 134 135 136 137 138 139 140 141 142 |