Code snippets-1

======================================================

while  ,match-case & except 

======================================================

from logging import exception


words=[]


while True:

   print("\n\n1.add a word to list")

   print("2.show the list\n3.exit loop")

   print ()

   try:

       action_num = int(input("Choose an action number: "))

       prompt = "Enter a word: "

       match action_num:

           case 1:

               words.append(input(prompt))

           case 2:

               for word in words:

                   if isinstance(word,str): #----------------------------------type checking

                       print(word.capitalize(),end=" ")

                       print (word.title(),end=" ")

                   else:

                       print("word is not string type")

           case 3:

               break

   except Exception as e:

       print("An error occurred",e)

   finally:

       print("End of try-except block.")



======================================================

enumerate & for

======================================================

for i, j in enumerate("Hello"):

   print(i,j)

result

0H

1e

2l

3l

4o


a=enumerate("a","b","c")

list(a)= [(0,a),(1,b),(2,c)]

------------------------------------------------------


for ch in "Hello":

   print(ch)

------------------------------------------------------


buttons = [('John', 'Sen', 'Morro'), ('Lin', 'Ajay', 'Filip')]

for first, second in enumerate(buttons):

   for name in second:

       print(first,name)

======================================================

list sort

======================================================


wait_list=["sen","ben","john"]

wait_list.sort()

print(wait_list)

wait_list.sort(reverse=True)

print(wait_list)


======================================================

file

======================================================


file = open('words.txt','w')

file.writelines('first\nsecond\nthird')

file.close()

file = open('words.txt','r')

text=file.read()

print(text)