代码之家  ›  专栏  ›  技术社区  ›  user3418284

将其写入文件的正确语法是什么?

  •  1
  • user3418284  · 技术社区  · 12 年前
    def guessingTime(answer, username):
        vdfile = open("victorydefeat.txt", "a")
        now = time.asctime(time.localtime(time.time()))
        victory = username + "successfully guess" + answer + "on" + now
        defeat = username + "was unable to guess" + answer + "on" + now
        print("That's 20! Time to guess.")
        guess = input("Is it a(n): ")
        if guess.lower() == answer:
            print("You got it! Congratulations!")
            vdfile.write(victory)
            vdfile.write("\n")
        else:
            print("Sorry, but the answer was", answer)
            vdfile.write(now)
            vdfile.write("\n")
        vdfile.close()
    
    def main():
        print("Welcome to 20 questions! The game where I (your humble program) will think of an object and you (the beloved user) will try to guess it!")
        username = print(input(("Now, before we begin, I'd like to know your name (for recording purposes): ")))
        infile1, infile2, answer = getAnswer()
        #startAsking(infile1, infile2)
        guessingTime(answer, username)
    
    main()
    

    对于“胜利=”行,错误消息为“不支持+='NoneType'和'str'的操作数类型”。我想写:“成功猜中了”。我该怎么做?

    2 回复  |  直到 12 年前
        1
  •  1
  •   unholysampler    12 年前

    print() 不返回值。正因为如此 username 正在设置为 None .

    input() 将打印传递的字符串并返回输入的文本。您只需要以下内容:

    username = input("Now, before we begin, I'd like to know your name (for recording purposes): ")
    
        2
  •  0
  •   jonrsharpe    12 年前

    你可以使用 time.asctime() ,默认为本地时间。此外,字符串格式是您的朋友:

    "{0} guessed {1} on {2}".format(username, answer, time.asctime())
    

    然而,你的论点之一 username 或 answer 是 None (正如unholysampler解释的那样)这就是为什么会出现这种特定错误的原因。