2017-05-25 39 views
0

这是我的Python程序代码,但我不能写marks.txt即时得到错误像这样的演出后,X Python代码PYT类型错误:无法转换“诠释”对象隐含str的

file = open('marks.txt','w') 
s1marks=0 
s2marks=0 
index=int(input("index:")) 
if index != -1: 
    s1marks=str(input("subject1marks:")) 
    s2marks=str(input("subject2marks:")) 
    x=str("index is"+index+s1marks+s2marks) 
    file.write(x) 
    index=int(input("next index:")) 
    file.close() 

错误

指数:10 subject1marks:8个 subject2marks:5 回溯(最近通话最后一个): 文件 “”,10号线,在 类型错误:无法转换 '诠释' 对象为str隐含

回答

0
在类别

正是它在锡说

变化

x=str("index is"+index+s1marks+s2marks) 

x = "index is" + str(index) + s1marks + s2marks 

,但不是唯一的变化我会做:

  • 您assigne到s1markss2marks变量,那么以后你采取一个input()分配string其中整数0

  • 也转换了input()str()明确,而输入已经被定义的字符串。

  • 在写入文件file.write(x)之后,您还需要另一个index,但是您不会再循环,这是因为您没有定义循环。如while

  • 处理文件,你应该使用with

  • 你不需要指定变量x只是为.write()的语句,除非你做别的事情与x后,在这个代码你不

  • 你需要做一个新的行字符写入文件时(这是假设我做了,也许你想要的输出文件都在同一行),这是'\n'

  • 你在你的代码混合"',最好是选择一个,并坚持下去

  • 你不要在你的write()x=插入空格,你应该以增强输出文件的可读性。

全部放在一起:

with open('marks.txt', 'w') as openfile: 
    index = int(input('index:')) 
    while index > 0: 
     s1marks = input('subject1marks:') 
     s2marks = input('subject2marks:') 
     openfile.write('index is ' + str(index) + ' ' + s1marks + ' ' + s2marks + '\n') 
     index = int(input('index:')) 
1

您必须先将整数索引转换为字符串。 Python不明白,你想连接4串,因为是一个整数:

x = "index is" + str(index) + s1marks + s2marks 

我希望它能帮助,

相关问题