我是python的新手。我想运行此代码,但是遇到语法错误,我不知道如何解决。我正在运行它
http://webvr.virtualskillslab.de/0.8.0
names=['A','B','C']
cars=['mercedes','porshe','hyundai']
numbers=[1,2,3]
for name in names:
file_name=names+".txt"
text_file = open(file_name, "w")
for car in cars:
print(cars)
for number in numbers:
txt2write=name+" has "+str(number)+" "+car
print(name+" has "+str(number)+" "+car)
text_file.write("%s \n" %(txt2write))
text_file.close()
print("That's all.")
有什么主意吗?再说一遍,这是我的第一个代码..(就像我对Python完全陌生,对嵌套循环一无所知)
答案 0 :(得分:1)
缩进不正确,第file_name = names + "txt"
行也应使用name
而不是names
。这是完整的固定代码:
names=['A','B','C']
cars=['mercedes','porshe','hyundai']
numbers=[1,2,3]
for name in names:
file_name=name+".txt"
text_file = open(file_name, "w")
for car in cars:
print(cars)
for number in numbers:
txt2write=name+" has "+str(number)+" "+car
print(name+" has "+str(number)+" "+car)
text_file.write("%s \n" %(txt2write))
text_file.close()
print("That's all.")
答案 1 :(得分:-1)
names=['A','B','C']
cars=['mercedes','porshe','hyundai']
numbers=[1,2,3]
for name in names:
file_name=name+".txt" # leave 4 spaces for the outermost level
text_file = open(file_name, "w")
for car in cars:
print(cars) # leave 8 spaces for the innermost level
for number in numbers:
txt2write=name+" has "+str(number)+" "+car
print(name+" has "+str(number)+" "+car)
text_file.write("%s \n" %(txt2write))
text_file.close()
print("That's all.")
获取正确的for循环缩进。
file_name=names+".txt"
也应该是file_name=names+".txt"