所以我定义了这些:
def highscorenumber():
file = open('GUESS THE NUMBER HIGHSCORE NUMBER.txt', 'r')
highscorenum = file.readline(1)
def highscorename():
file = open('GUESS THE NUMBER HIGHSCORE NAME.txt', 'r')
highscorenum = file.readline(1)
这些保存在与程序相同的目录中。打开时"GUESS THE NUMBER HIGHSCORE NUMBER.txt"
说:"1"
"GUESS THE NUMBER HIGHSCORE NAME.txt"
在打开时显示"max"
。
然而,当我跑步时:
print("The current highscore is",highscorenumber,"set by",highscorename)
它说:
The current highscore is <function highscorenumber at 0x0000000002D46730> set by <function highscorename at 0x0000000001F67730>
为什么会这样说而不是"The current highscore is 1 set by max"
?
答案 0 :(得分:3)
因为您没有调用函数,所以Python正在打印函数对象本身的表示:
>>> def f():
... return 1
...
>>> print(f)
<function f at 0x015E1618>
>>> print(f())
1
>>>
如上所示,您需要调用函数以打印其返回值:
print("The current highscore is",highscorenumber(),"set by",highscorename())
您还应该从每个函数返回readline
的调用:
def highscorenumber():
file = open('GUESS THE NUMBER HIGHSCORE NUMBER.txt', 'r')
return file.readline(1)
否则,默认情况下,函数将返回None
。
最后,我使用with-statements打开文件:
def highscorenumber():
with open('GUESS THE NUMBER HIGHSCORE NUMBER.txt', 'r') as file:
return file.readline(1)
这将确保您在完成它们后关闭它们。
答案 1 :(得分:-2)
使用camel case ...它是python读取内容的方式。 Camel case是名称中没有空格的地方......另外,不要忘记关闭文件
例如名称为:
GuessTheNumberHighscoreName.txt
或
Guess_The_Number_HighScore_Name.txt