尝试将特定值打印到txt fi的python代码

2024-05-06 15:53:44 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

'def'/myName = input() \r
/myName = 'Albert' \r
text_file = open("C:\Output.txt", "w") \r
text_file.write("myName") \r
text_file.close()

我的意思是,这是我第一次用python为学校作业编写代码,但在第一次之后它一直给我这个“SyntaxError:意外字符后的行继续字符”。谁能解释一下/帮我一下吗?你知道吗

-唐尼


Tags: 代码texttxtcloseinputoutputdef作业
2条回答

您的代码表明您根本不熟悉Python的语法及其工作方式。以下是您的错误解释(按您的要求):

 'def'/myName = input() \r

def周围不需要撇号,myName不需要正斜杠。不能将函数设置为在第一行执行某些操作-这是正确的语法:

def foo():
    bar = input('carrot: ')
    print(bar)

此外,在执行任何操作之前,需要将input存储在变量中;input接受字符串。你不需要在每一行之后都有回车。在括号后面,你需要一个冒号。你知道吗

  /myName = 'Albert' \r

不能将函数设置为等于字符串。你知道吗

text_file = open("C:\Output.txt", "w") \r
text_file.write("myName") \r

myName是一个变量,而不是字符串,因此不需要引号。你知道吗

 text_file.close()

以下是工作代码:

myName = input('Name: ')               # ask for input, which will be stored in myName
text_file = open('C:\output.txt', 'w') # open the output file in write mode
text_file.write(myName)                # write myName to the output file

我建议在进一步尝试之前先阅读official Python tutorial。你知道吗

myName = raw_input('type name: ')
with open("output.txt", "w") as textfile:
    textfile.write(myName)

相关问题 更多 >