我想知道如何正确编写try except语句?

时间:2015-01-10 02:20:16

标签: python-3.x

对于这段代码,我试图导入一些数字,然后将它们导出程序(工作正常)。我遇到的问题是代码在代码读完.txt文档之前退出do while语句,我认为是因为try expect语句。我试图解决这个问题需要帮助。

print("This program shows acceleration over time and puts them in a text file.")
speed = 0
t = 0
acc = 0
file = open("Output_FileP3v2.txt", "w")
file2 = open("P3v2_Input.txt","r")
dt = float(file2.readline())
while (dt != ""):
    file.write('t,acc,speed\n')
    file.write(str(t) + "," + str(acc) + "," + str(speed) + "\n")
    while(speed < 100):
        acc = acc + 5
        speed = speed + acc * dt
        t = t + dt
        file.write(str(t) + "," + str(acc) + "," + str(speed) + "\n")     
    acc = 0
    while (t <= 5):                     
        t = t + 1
        file.write(str(t) + "," + str(acc) + str(speed) + "\n")       
    while (speed > 0):                  
        acc = acc - 5
        speed = speed + acc * dt
        t = t + dt
        file.write(str(t) + "," + str(acc) + "," + str(speed) + "\n")  
    try :
        dt = float(dt = read.readline())
        print
    except:
        dt = ""               #here is where I think I am having the trouble. the program is setting it to "" before the code is finished reading the .txt document and I dont know why.
    print ("hi")              #to show how many times the while statement ran.
print ("The program just sent a list of code in a text document to where the program file is saved.")
file.close()
file2.close()

1 个答案:

答案 0 :(得分:2)

在Python 3中,作为函数的print语句需要括号而不仅仅是print。更改为print(),您的方法应该有效。

有关更多信息,请查看下面的文档,了解有关如何在python 3中使用函数完全替换print语句的更多信息:https://docs.python.org/3.0/whatsnew/3.0.html