You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python输出插入空行、输入输出分隔及py文件运行崩溃问题咨询

问题1:输入与输出区域插入空行分隔

Python中print()函数不传入任何参数时,会默认输出一个换行,也就是在终端打印一行空白。你只需要在所有输入收集完成、正式开始打印输出内容之前,添加对应数量的空print()语句即可实现分隔效果。

  • 若需要保留2行空白间隔,就连续写2次print(),可以直接参考示例的空白高度调整语句数量
  • 也可以在输出的第一行字符串前加换行符\n实现相同效果,比如print('\n\nAlex Partida Stock Transaction App'),但单独写空print()的写法可读性更强,更方便后续调整。
问题2:双击.py文件运行到第6个输入后闪退

这个现象不是程序崩溃,是Windows系统下直接双击运行Python脚本的默认行为导致的:

  • 双击运行时,系统会拉起一个临时Python终端窗口执行代码,一旦程序运行到最后一行代码,这个临时窗口会立刻自动关闭
  • 你遇到的“第6个输入后出问题”刚好对应最后一个输入项:输完第6项按回车后,程序会瞬间执行完所有后续的打印逻辑,直接运行到代码末尾触发窗口关闭,你根本来不及看到输出内容,就误以为是程序崩溃
  • 手动在CMD中执行命令、或是在IDLE中运行时,终端环境不会随着脚本运行结束自动关闭,所以可以正常看到完整输出

解决方法

在整个代码的最末尾添加一行等待用户输入的语句,让程序执行完所有输出逻辑后暂停,等你手动按回车再关闭窗口即可,示例代码:

input("\n按回车键退出程序...")
修改后完整可运行代码
# This program will be used to determine
# Calculations for a stock transaction

# The inputs
Shares_Bought = int(input('Enter shares purchased: '))
SharePrice_B = float(input('Enter purchase price of shares: '))
B_Commission = float(input('Enter broker buy commission: '))
Shares_Sold = int(input('Enter shares sold: '))
SharePrice_S = float(input('Enter sell price of shares: '))
S_Commission = float(input('Enter broker sell comission: '))

#CONSTANTS?
TOTAL_PURCHASE = Shares_Bought * SharePrice_B
TOTAL_SALE = Shares_Sold * SharePrice_S
TOTAL_SALES_COMMISSION = (Shares_Bought * SharePrice_B) * (B_Commission / 100) + (Shares_Sold * SharePrice_S) * (S_Commission / 100)

# 插入空行分隔输入输出区域
print()
print()

# The outputs 
print('Alex Partida Stock Transaction App')
print(f'Joe Paid: ${Shares_Bought * SharePrice_B:,.2f}')
print(f'Purchase Commission: ${(Shares_Bought * SharePrice_B) * (B_Commission / 100):,.2f}')
print(f'Joe sold at: ${Shares_Sold * SharePrice_S:,.2f}')
print(f'Sales Commission: ${(Shares_Sold * SharePrice_S) * (S_Commission / 100):,.2f}')
print(f"Joe's Profit: ${(TOTAL_SALE - TOTAL_PURCHASE) - TOTAL_SALES_COMMISSION:,.2f}") 

# 防止双击运行时窗口自动关闭
input("\n按回车键退出...")

内容的提问来源于stack exchange,提问作者goonys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 10:57:27