0
file = open(r'd:\holiday_list.txt', 'w')
date = ''
while(date != '0'):
    date = input('\nEnter Date (YYYYMMDD) : ')
    date = date[:4] + '-' + date[4:6] + '-' + date[5:]
    file.write(date)
print('Job Done!')
file.close()

This program is supposed to take dates (eg:20112016) as input and write it to a file. The problem is the program does not exit the while loop. If i enter a 0, it prompts me to enter another date.

1
  • 1
    The line date = date[:4] + '-' + date[4:6] + '-' + date[5:] modifies the '0' to '0--'. Commented Mar 21, 2018 at 17:36

2 Answers 2

2

You have your check in the wrong place: you manipulate the date as soon as you read it in, and the result is no longer '0' when you get back to the top of the loop. Try this:

date = input('\nEnter Date (YYYYMMDD) : ')
while(date != '0'):
    date = date[:4] + '-' + date[4:6] + '-' + date[5:]
    file.write(date)
    date = input('\nEnter Date (YYYYMMDD) : ')

ANother check is the most basic of debugging: put in a print command to show exactly what you read in. Perhaps something like

print("date is ||", date"||")

The vertical bars will show any leading or trailing white space, such as the newline character. (Get rid of that with the strip method.)

Sign up to request clarification or add additional context in comments.

1 Comment

this works. the dates are qetting appended to one line though in thee text file. eg. 0401-19-9910408-19-989. I can add a new line. thanks a lot.
0

An alternative solution to Prune's is to use an if statement with a break:

    while(True):
        date=input('\nEnter Date (YYYYMMDD) : ')
        if(date=='0'):
            break
        ...#your work here

This way you don't have to have an additional input outside the loop.

2 Comments

... but you have an extra check in your logic. It's a style trade-off.
Indeed, it's more of a personal choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.