【问题标题】:How to print twice on the same line using functions如何使用函数在同一行上打印两次
【发布时间】:2016-01-28 20:50:07
【问题描述】:
def Drawstars(spaces, stars):
          spaces = int(spaces) - 1
          stars = int(stars)
          print(line = " " * spaces + "*" *stars)

# i want this to be printed once
s = 3
st = 3
Drawstars(s, st)

#i want these to be printed twice

s = 3
st = 1
Drawstars(s, st)

s= 2
st = 2
Drawstars(s, st)

我如何将底部的两个在同一条线上工作两次而顶部的只工作一次。 我得到的是:

   *
   *
   **

但我想要的是:

   *
   * **

任何帮助将不胜感激

【问题讨论】:

标签: function python-3.x


【解决方案1】:

如果您使用函数sys.stdout.write(),它可以打印而无需添加新行。

如果你有这样的功能

def DrawstarsOneline(spaces, stars):
      spaces = int(spaces) - 1
      stars = int(stars)
      sys.stdout.write(" " * spaces + "*" *stars)

然后你可以这样调用你的代码

s = 3
st = 1
DrawstarsOneline(s, st)

s= 2
st = 2
Drawstars(s, st)

它会产生所需的输出。

您需要在代码顶部使用以下行导入 SYS 模块: import sys

【讨论】:

    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2018-12-28
    • 2017-02-20
    • 1970-01-01
    • 2020-09-21
    • 2018-08-26
    相关资源
    最近更新 更多