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

如何修改Python代码以仅调用一次print函数?

Fix: Call print() Only While Keeping Your Original Logic

Hey there! Your existing code works exactly as intended, but since the requirement is to use only one print() call, we can simplify things with Python's ternary conditional expression. Here's how to adjust it:

Modified Code

number = input('Please enter a number: ')
number = int(number)
print(number if number > 1 else -number)

How It Works

The ternary expression number if number > 1 else -number acts like a compact inline if-else statement. It checks the condition number > 1:

  • If the condition is true, it returns the original number
  • If the condition is false, it returns -number

This computed value is passed directly to print() in a single call, so we meet the requirement without changing the original logic at all.

If you prefer a more explicit, readable approach, you can also store the result in a variable first before printing:

number = input('Please enter a number: ')
number = int(number)
output_value = number if number > 1 else -number
print(output_value)

Either version will produce the exact same output as your original code, but with only one print() invocation.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:02:44