I have a program which takes a series of strings from user input and should print "Yes" if the strings entered are in alphabetical order and "No" if not. The program ends by the user entering an empty input. I can do this when I specify the number of inputs it should have, eg 2:
finished = False
while not finished:
print("Please enter a string: ")
s = input()
x = input()
if len(s) != 0:
if s < x:
print("Yes")
else:
print("No")
else:
finished = True
However I can't seem to get my code to work when there is an indefinite amount of strings that can be entered. My current working method is to append all the strings to a list and perform the checks there, but I'm not sure exactly how to write the if statement to check this:
lst = []
i = range(len(lst))
finished = False
while not finished:
print("Please enter a string: ")
s = input()
lst.append(s)
if len(s) != 0:
if lst[i:] < lst[i: - 1]:
print("Yes")
else:
print("No")
else:
finished = True
Is there an easy way to achieve this without deviating too far from the intended structure above?
lst
is a list of strings, slicing syntax on that will get you a list of strings back. But you want a string instead. Since you're appending to the list, the latest string appended will be present in the [-1]
index, and the previous one will be present in [-2]
index.
Change lst[i:] < lst[i: - 1]
to lst[-2] < lst[-1]
There's still another problem though, in the first iteration lst[-2]
does not exist, because there is only one string that has been inputted, to get rid of this - take one input and append
it to the list before the loop starts-
print("Please enter a string: ")
s = input()
lst.append(s)
finished = False
while not finished:
# rest of your code