2017-05-25 96 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 

我希望它能幫助,

相關問題