首页 > 解决方案 > 如果文件创建了所有数字,如何退出程序

问题描述

我有一个空白文本文件,我需要在其中输入 4 位 message_code 以及最后从 0-9/AZ 的单个数字。所以我可以为每个 message_code 拥有 36 个独特的组合。

我的代码将在 4 位 message_code 的末尾一个一个地写入这个随机数字,但是当所有 36 个组合都用完时,循环不会中断,它会进入无限模式。我想退出程序并向最终用户发送一些消息以输入除 0-9 或 AZ 之外的其他字符。

代码片段:

import random
import string
def checkInput(prompt):
    while True:
        try:
            a = input(prompt)
        except ValueError:
            print ("Sorry, I didn't understand that")
            continue
        if not a.strip():
            print ("Whitespaces encountered, please enter proper value.")
            continue
        else:
            break
    return a

def addnew():
    count=int(input("How many new messagecode you want to create? "))
    for m in range(0,count):
        Mesgcode = checkInput("Enter the mesgcode")
        Rkey = random.choice(string.ascii_uppercase+string.digits)
        HCode = Mesgcode+Rkey
        with open('Host.txt') as f:
            z=f.read()

        def new():
            Rkey = random.choice(string.ascii_uppercase+string.digits)
            HCode=Mesgcode+Rkey
            return HCode

        while HCode in z:
            HCode = new()
        f1=open('Host.txt', "a")
        f1.write("New code added %s\r\n" % HCode)
        f1.close()
        m+=1

addnew()

Host.txt 文件将如下所示:

ABCD0
ABCD1
ABCD2
.
.
.
ABCD9
ABCDA
.
.
.
ABCDZ

当所有随机数字都用完后,用户应该会收到一条打印的消息Please use different character except 0-9/A-Z, all usage exhausted ,并且程序应该优雅地退出。

标签: python-3.xpython-2.7

解决方案


我认为您可以使用listdictionary保存可能的值。获取值时,将其从您的listor中删除dictionarylist如果或dictionary为空,请退出此程序。

此外:最好with open在循环外使用,否则每次进入循环时文件都会打开和关闭。


推荐阅读