简体   繁体   English

Python 2中的无限While循环

[英]Infinite While Loop in Python 2

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. 该程序应该以日期(例如:20112016)作为输入并将其写入文件。 The problem is the program does not exit the while loop. 问题是程序没有退出while循环。 If i enter a 0, it prompts me to enter another date. 如果我输入0,则提示我输入另一个日期。

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. 您将支票放在错误的位置:读入日期后立即操作日期,回到循环顶部时结果不再为'0' 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命令以准确显示所读内容。也许类似

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.) (使用strip方法摆脱它。)

An alternative solution to Prune's is to use an if statement with a break : Prune的替代解决方案是使用带有breakif语句:

    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. 这样,您不必在循环外有其他输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM