Python:如何使用if,for和while控制语句在“框架”中打印消息?真的很困惑

时间:2014-03-23 08:27:02

标签: python loops

用户输入一条消息,即他希望重复该消息的次数,  和框架的“厚度”。它在由'*','|'和' - '符号组成的框架内打印出消息。我的节目:

x = input("Enter the message:\n")
y = eval(input("Enter the message repeat count:\n"))`enter code here`
z = eval(input("Enter the frame thickness:\n"))


for top in range (z):
    print("|"*(z-1)+"+"+"-"*(len(x)+2)+"+"+"|"*(z-1))
for repeat in range(y):
    print("|"*z,x,"|"*z)
for bottom in range(z):
    print("|"*(z-1)+"+"+"-"*(len(x)+2)+"+"+"|"*(z-1))

示例输出,重复计数3,帧厚度2和消息:“Hello World”

|+-------------+|
|+-------------+|
|| Hello World ||
|| Hello World ||
|| Hello World ||
|+-------------+|
|+-------------+|

但这不是必需的框架。这就是它的样子:

+---------------+
|+-------------+|
|| Hello World ||
|| Hello World ||
|| Hello World ||
|+-------------+|
+---------------+

我使用3种不同的循环是否正确?我正在努力“双”循环框架的顶部和底部部分,以便在每个框架级别,每个角落中有一个“+”,沿着框架的顶部和底部部分有一个“ - ”和一个“|”沿着左右两边。我认为这将是一个类似的概念,打印出底部的金字塔和顶部的倒金字塔,但这让我无处可去。我上面做的程序是最接近期望结果的程序。如您所见,顶部和底部的每个“框架”都不同。 ;(

以下是实际指示:

编写程序以在连续行上重复的消息周围绘制一个框架(由字符+ - |组成)。消息前后有一个空格,同心框之间没有空格。

请帮忙。 Python V3.x

4 个答案:

答案 0 :(得分:0)

您可以将循环变量用作深度提示:

x = " %s "%x # Add the spaces
for depth in range(z):
    # depth will be 0 on the first iteration, then 1
    print("|"*depth+"+"+"-"*(len(x)+2*(z-depth-1))+"+"+"|"*depth)
for repeat in range(y):
    print("|"*z+x+"|"*z)
for depth in reversed(range(z)):
    # reverse the depth values to start from the inner frame
    print("|"*depth+"+"+"-"*(len(x)+2*(z-depth-1))+"+"+"|"*depth)

显然不止一种方法,这是一个反复的例子:

您可以使用一个功能,该功能将消息作为输入并输出具有1级帧的相同消息,然后根据您的厚度需要多次应用它。

def _one_frame(text):                 # text is supposed to be a list of lines
    lt = len(text[0])
    horz = '+' + '-'*lt + '+'         # Make the horizontal line +-------+
    result = [horz]                   # Top of the frame
    for line in text:
        result.append( '|'+line+'|' ) # Add the borders for each line
    result.append(horz)               # Bottom of the frame
    return result

def frame(text, repeat, thickness):
    text = [" %s "%text]*repeat       # add spaces and repeat as a list
    for i in range(thickness):
        text = _one_frame(text)       # draw one frame per iteration
    return '\n'.join(text)            # join lines

print(frame('Hello World', 3, 2))

答案 1 :(得分:0)

首先,您需要将z替换为top。然后,有更多的逻辑,想一想:

for top in range(z):
    print '|'*top + "+" + "-"*(x+2 + (z-1)*2 - top*2) + "+" + "|"*top 

答案 2 :(得分:0)

首先,明确地命名变量,使其更容易理解和纠正:

message = input("Enter the message:\n")
repeats = eval(input("Enter the message repeat count:\n"))
thickness = eval(input("Enter the frame thickness:\n"))

然后你需要让你的框架顶部做到这一点:

widthWithFrame = len(message) + thickness*2

for i in range(0, thickness) :
  print("|"*i + "+" + "-"*(widthWithFrame-(i+1)*2) + "+" + "|"*i)

其余我认为你可以从中找出答案。请注意,您的示例输出包含代码中未包含的“Hello World”周围的额外间距,因此如果您想允许,可能需要从“ - (i + 1)* 2”中删除“+1”。< / p>

答案 3 :(得分:0)

使用__str__方法进行字符串表示的面向对象解决方案。

class MultiMessage(object):
    """represents the repeated message"""
    def __init__(self, text, count):
        self.text = text
        #self.text = " %s " % text #optionally add some spaces
        self.count = count

    def message(self):
        """data representation is a simple list"""
        return [self.text] * self.count

    def __str__(self):
        return "\n".join(self.message())

class Frame(object):
    """a message wrapped in any number of frames"""
    def __init__(self, msg, thickness):
        self.msg = msg
        self.thickness = thickness

    @staticmethod
    def wrap(message):
        """wrap an array of data with a single frame and return as new data"""
        rows = len(message)
        cols = len(message[0])
        top = ''.join(['+'] + ['-' * cols] + ['+'])
        return [top] + ["|%s|" % row for row in message] + [top]


    def __str__(self):
        """wrap message and output a string"""
        result = self.msg.message()
        for i in xrange(self.thickness):
            result = self.wrap(result)
        return "\n".join(result)

现在可以像在您的示例中一样轻松使用。

message = raw_input("Enter the message:\n")
count = int(raw_input("Enter the message repeat count:\n"))
thickness = int(raw_input("Enter the frame thickness:\n"))

m = MultiMessage(message, count)
f = Frame(m, thickness)

print f