我想知道如何正确编写 try except 语句?
I was wondering how to correctly write a try except statement?
对于这段代码,我试图导入一些数字,然后将它们从程序中导出(工作正常)。我遇到的问题 运行 是代码在完成读取 .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()
在Python 3 中,作为函数的print 语句需要括号,而不仅仅是print
。更改为 print()
,您的方法应该有效。
有关更多信息,请查看下面的文档以了解有关如何在 python 3 中将打印语句完全替换为函数的更多信息:https://docs.python.org/3.0/whatsnew/3.0.html
对于这段代码,我试图导入一些数字,然后将它们从程序中导出(工作正常)。我遇到的问题 运行 是代码在完成读取 .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()
在Python 3 中,作为函数的print 语句需要括号,而不仅仅是print
。更改为 print()
,您的方法应该有效。
有关更多信息,请查看下面的文档以了解有关如何在 python 3 中将打印语句完全替换为函数的更多信息:https://docs.python.org/3.0/whatsnew/3.0.html