当我在IDLE中运行我的脚本时它运行完美,但是当我将其保存为.py文件并尝试从文件夹中打开它时,它会闪烁一秒钟然后立即关闭。为什么会发生这种情况?我该如何解决?
# average.py
def main():
print("This program will calculate your final grade for the class.")
assignment1= eval(input("What is your assignment 1 score?"))
assignment2= eval(input("What is your assignment 2 score?"))
assignment3= eval(input("What is your assignment 3 score?"))
assignment4= eval(input("What is your assignment 4 score?"))
assignment5= eval(input("What is your assignment 5 score?"))
assignment6= eval(input("What is your assignment 6 score?"))
assignment7= eval(input("What is your assignment 7 score?"))
assignment8= eval(input("What is your assignment 8 score?"))
assignment9= eval(input("What is your assignment 9 score?"))
assignment10= eval(input("What is your assignment 10 score?"))
midterm= eval(input("What is your midterm exam score?"))
final=eval(input("What is your final exam score?"))
participation= eval(input("What is your participation score?"))
average= (((assignment1 + assignment2 + assignment3 + assignment4 + assignment5 + assignment6 + assignment7 + assignment8 + assignment9 + assignment10 + midterm + final + participation)/420)*100)
print("You final class grade is", average)
答案 0 :(得分:2)
添加样板:
if __name__ == '__main__':
main()
在你的代码之后。
答案 1 :(得分:0)
首先应打开命令提示符,然后将脚本拖到其上以运行它。否则当程序结束时窗口关闭。
编辑:并执行@sundance建议的内容。
答案 2 :(得分:0)
首先,您是否正在调用main
函数?
我的意思是,你是否在代码的末尾添加了main()
?如果是,问题是python IDLE运行脚本然后等待执行新代码。 python.exe不是这种情况。你必须让翻译等待。执行此操作的常用方法是在代码末尾添加行raw_input()
,这将强制解释器在关闭之前等待(不需要的)用户输入,从而将结果打印到屏幕,直到有人输入某些内容为止进入它并按下返回。
答案 3 :(得分:0)
@sundance是对的。您的代码只定义了一个函数,但从不调用它,因此运行脚本时没有任何反应。你需要调用函数来执行它的主体,因此需要main()
调用。
另外,您的代码可以按如下方式进行优化:
tasks = ['assignment {}'.format(i) for i in range(1, 11)] + [
'midterm exam', 'final exam', 'participation']
sum_scores = sum(
float(input('What is your {} score? '.format(task)))
for task in tasks)
average = sum_scores / 420 * 100
print('Your final class grade is', average)
答案 4 :(得分:0)
在average.py
中,您只是定义函数。因此,当您执行脚本时,只有函数定义而没有函数调用。您需要在脚本末尾调用main()
函数。只需在代码末尾添加main()