while loop: 'no output' issue

Viewed 99

My task is to: "Write a program that reads and prints out all lines that start with a given letter. The file path and starting letter will be given as command-line arguments. You may assume that all command-line arguments will be valid"

e.g.

$ cat cats.txt
calico
siamese
ginger
cute, cuddly

$ python3 filter.py cats.txt c
calico
cute, cuddly

$ python3 filter.py cats.txt g
ginger

My code right now looks like:

import sys
with open("cats.txt", "r") as f:
   a = f.readlines()
   word_no = 0
   l = len(a) - 1
   while word_no <= l:
       if (a[word_no][0]) == sys.argv[1]:
           print (a[word_no])
       word_no += 1

However, I'm not passing the test cases as my code shows up with no output, even though it works with the sample textfile? enter image description here

1 Answers

There seems to be a few mistakes in your code - hard-coded file path, incorrect index of sys.argv and printing line with \n. Corrected code:

import sys
with open(sys.argv[1], "r") as f:
   a = f.readlines()
   word_no = 0
   l = len(a) - 1
   while word_no <= l:
       if (a[word_no][0]) == sys.argv[2]:
           print (a[word_no].strip())
       word_no += 1

Also, a better way to write this code would be:

import sys
with open(sys.argv[1], "r") as f:
    for line in f:
        if line[0] == sys.argv[2]:
            print(line.strip())
Related