我正在尝试创建一个基本的登录程序,要求用户输入用户名和密码,并在日志文件中记录任何正确或错误的文本。我遇到的问题是,当我尝试使用多个用户名和密码组合时,我会遇到语法错误。
#login program
output = open("logfile.txt", 'a')
login = input("please enter the correct username and password\n")
a = "username password"
b = "username1 password1"
if a in login:
print("successfully logged in")
import time
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody successfully logged in at ")
output.write(localtime)
output.write("\n")
output.close()
if b in login:
print("successfully logged in")
import time
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody successfully logged in at ")
output.write(localtime)
output.write("\n")
output.close()
else:
print("access denied.")
import time
output = open("logfile.txt", "a")
localtime = time.asctime(time.localtime(time.time())
output.write("Somebody unsuccessfully logged at ")
output.write(localtime)
output.write("\n")
output.close()
错误:
File "test.py", line 28
output.write("Somebody unsuccessfully logged at ")
^
SyntaxError: invalid syntax
答案 0 :(得分:7)
您在else:
区块中缺少右括号:
output = open("logfile.txt", "a")
localtime = time.asctime(time.localtime(time.time())
#-----------------^
这会导致Python在下一行报告语法错误。您需要做的只是添加一个)
;你有3个开放的parens,但只有2个关闭。
答案 1 :(得分:2)
为了向Martijn的答案添加更多内容,python解释器在括号内删除了换行符。所以,python解释器,而不是看到
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody unsuccessfully logged at ")
(添加了正确的括号),解释器实际上看到了
localtime = time.asctime(time.localtime(time.time()) output.write("Somebody unsuccessfully logged at ")
其中output.write("Somebody unsuccessfully logged at ")
是time.asctime的另一个参数。这显然会引发有关无效语法的错误。我希望这能让你更多地了解正在发生的事情,以及为什么错误出现在预期的一行之后。