Home > database >  Need help in while loop with conditional statement
Need help in while loop with conditional statement

Time:03-09

Here is the problem:

Write a Python program that reads a series of lines one by one from the keyboard (ending by an empty line) and, at the end, outputs 'Yes'once if the lines before the empty line were ordered by length from shorter to longer,otherwise it outputs 'No' (again, only once and at the end).

Below is my code. I'm not getting expected result. I tried to debug and understand what is going wrong, but unable to fix it.

finish=False
while not finish:
  line = input('Enter the line: ')
  old_line=line
    
  if len(new_line)!=0:

    new_line=line
  else:
   finish=True

if len(new_line)>len(old_line):
  print('Yes')
    
else:
  print('No')

CodePudding user response:

This should do the task

while True:
    line = input('enter line!')
    if line:
        lines.append(line)
    else:
        print('yes' if (len(lines[-2]) > len(lines[-1])) else 'no')
        break

CodePudding user response:

lines = []
while True:
    line = input('enter line!')
    if line:
        lines.append(len(line))
    else:
        print('yes' if (sorted(lines, reverse=True)  == lines) else 'no')
        break

this will work if all the lines has to be considered for comparison.

  • Related