【问题标题】:Why can't i re-run a function in python?为什么我不能在 python 中重新运行一个函数?
【发布时间】:2012-01-15 04:03:18
【问题描述】:

我刚刚完成了我的家庭作业写作程序,现在我遇到了一个非常烦人的问题

我这样做了,所以当一个函数完成时,它会询问它是否要重新运行主函数,当我这样做时,然后运行另一个函数(对不起,如果我在措辞上很糟糕)该函数什么都不做。有什么我可以做的吗?

这是我的代码

agenda=open("agenda.txt","a") #open the notepad file
def choice(): #pick the period
    choice=input("type write, read, or clear\n")

    if choice=="read":
        read()
    elif choice=="write":
        write()
    elif choice=="clear":
        clear()
    else:
        print("Invalid Choice")


def write(): #write the homework
    per=input("What period is it")
    hw=input("What is the homework")
    if per=="1":
        agenda.write("Period 1:")
        agenda.write(hw)
        agenda.write("\n")
    elif per=="2":
        agenda.write("Period 2:")
        agenda.write(hw)
        agenda.write("\n")
    elif per=="3":
        agenda.write("Period 3:")
        agenda.write(hw)
        agenda.write("\n")
    elif per=="4":
        agenda.write("Period 4:")
        agenda.write(hw)
        agenda.write("\n")
    elif per=="5":
        agenda.write("Period 5:")
        agenda.write(hw)
        agenda.write("\n")
    elif per=="6":
        agenda.write("Period 6:")
        agenda.write(hw)
        agenda.write("\n")
    elif per=="7":
        agenda.write("Period 7:")
        agenda.write(hw)
        agenda.write("\n")
    elif per=="8":
        agenda.write("Period 8:")
        agenda.write(hw)
        agenda.write("\n")
    else:
        print("Non existant period")
    again=input("Would you like to read the homework, clear, or read again? (yes or no)")
    if again=="yes":
        choice()
    elif again=="no":
        print("\n")



def clear():#clear the whole thing
   ajenda = open('agenda.txt', 'r+')
   ajenda.truncate()
   again=input("Would you like to read the homework, clear, or read again? (yes or no)")
   if again=="yes":
       choice()
   elif again=="no":
       print("\n")

def read():#read the homework
    read=open("agenda.txt","r")
    readf=read.read()
    print(readf)
    read.close
    again=input("Would you like to read the homework, clear, or read again? (yes or no)")
    if again=="yes":
        choice()
    elif again=="no":
        print("\n")

choice()
agenda.close()

【问题讨论】:

  • 程序的输出以及预期的结果可能会有所帮助。
  • 我认为你想使用 raw_input() 而不是 input()
  • @VaughnCato:raw_input 在 python 3 中消失了。

标签: python-3.x


【解决方案1】:

我在 python2.7 中运行了你的代码,因为我现在没有 python3。

我的猜测是你运行了你的代码,写了一些作业,然后你要求阅读它,但没有任何显示。当您写入文件时,出于性能原因,在提供一定数量的数据或关闭文件之前,缓冲区不会进入文件。

如果您测试您的代码然后退出程序,您将在文件中找到您的数据。您可以考虑在 write 方法中添加一个 flush() 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2019-08-28
    相关资源
    最近更新 更多