Python打印功能输出多次 [英] Python printing function output multiple times

查看:67
本文介绍了Python打印功能输出多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来完成某些python挑战.我创建了该程序,它基本上完成了我需要做的所有事情,除了它有一个怪异的怪癖.它会多次打印我想要的输出.

I'm making a program to accomplish a certain python challenge. I created the program, and it basically does everything I need it to do, except it's got one weird quirk; it prints the output I want multiple times.

cmdname = input("Enter the name of your command.\n>")
print("Enter options one by one. If the option has an argument, put a * at the end of the option. When done entering options, enter \"q\".")
oplist = ""
oplist += cmdname + " " 
def prgm(): 
    global oplist
    while 2 + 2 == 4:
        user = input(">")
        if user[0] == "-":
            if "*" in user:
                oplist += user[0:len(user) - 1] + " " 
                print("Now, enter the option's argument.")
                user = input(">")
                oplist += user[0:len(user) - 1] + " " 
                print("Option successfully added.")
                prgm()
            else: 
                oplist += user + " " 
                print("Option successfully added.")
                prgm()
        elif user == "q":
            print("Enter the command argument.")
            user = input(">")
            oplist += user
        else:
            print("Error. You didn't enter an option.")
            prgm()
        break
    print(oplist)
prgm()

输出输出的次数似乎取决于用户指定的选项数量,但我不知道为什么.另外,在IDLE中运行程序时,如果我在函数完成后手动打印(oplist),则IDLE会像我希望的那样在一行上打印一次输出.为什么会这样呢?

The amount of times the output is printed seems to depend on how many options the user specifies, but I don't know why. In addition, when running the program in IDLE, if I manually print(oplist) after the function is finished, IDLE prints the output once on one line, like I intended it to. Why exactly is that the case?

推荐答案

print(oplist)移动到函数的末尾.由于您正在使用递归,因此该行被多次调用.

Move print(oplist) outside the function, to the last line of the program. Since you are using recursion, this line is called multiple times.

这篇关于Python打印功能输出多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆