所以我试图在我的工作产品(三角形制造商)中添加一些代码,如果程序允许的话,你可以在三角形的中间添加一些文字。到目前为止,我已经添加了正确数量的x和缩进的文本,但程序仍然输出x的原始中间行。例如,Triangle(3," M")将输出
x
xxx
xMx
xxxxx
而不是
x
xMx
xxxxx
这就是我想要的。我尝试在x == textrow - 1时使用break但是这似乎不起作用我觉得我要做的就是以某种方式打破循环,用x&#39跳过用户的文本跳过计算机通常会打印xxx并继续运行的部分。但我不知道该怎么做。 这是我的代码,唯一真正相关的部分是"如果x> 1" (我知道这可能是你见过的效率最低的东西,但我是初学者,我会按照我的理解行事。)
def Triangle(height, text):
text1 = str(text)
number_of_x2 = (height - len(text)) / 2
if height % 2 == 0:
print "Please enter a height that is odd"
else:
stringTriangle = "x"
HT = ""
for x in range(height + height - 1):
HT += "x"
length_of_HT = len(HT)
length_of_HT = int(length_of_HT)
length_of_HT = len(HT) / 2
length_of_HT = int(length_of_HT)
indent_text_length = length_of_HT / 2
for x in range(height): #should be height change later
if x == 1:
stringTriangle = " " * length_of_HT + stringTriangle
print stringTriangle
if x > 1:
textrow = height / 2
for x in range(height):
if stringTriangle == HT:
break
if len(text) == len(stringTriangle):
break
if x == textrow:
text = ""
text = " " * number_of_x2
for x in range(number_of_x2):
text+="x"
text = text + text1
for x in range(number_of_x2):
text+="x"
print text
stringTriangle += "xx"
stringTriangle = stringTriangle[1:]
print stringTriangle
谢谢!
答案 0 :(得分:0)
我不确定你的代码是如何工作的,但是我调整了它直到它返回了我预期的结果。此外,我对有点难看的部分做了一些小改动。这应该做你想要的:
def Triangle(height, text):
number_of_x2 = (height - len(text)) / 2
if not height % 2:
print "Please enter a height that is odd"
else:
string_triangle = "x"
ht = "x" * (2 * height - 1)
length_of_ht = len(ht) / 2
indent_text_length = length_of_ht / 2
text_row = height / 2
# should be height change later
for x in range(height):
if x == 1:
string_triangle = " " * length_of_ht + string_triangle
print string_triangle
if x > 1:
for x in range(height):
if x == text_row - 1:
string_triangle += "xx"
string_triangle = string_triangle[1:]
continue
if x == textrow:
special_line = " " * (number_of_x2 + len(text) / 2) + "x" * number_of_x2 + text + "x" * number_of_x2
if not len(text) % 2:
special_line += "x"
print special_line
if string_triangle == ht or len(text) == len(string_triangle):
break
string_triangle += "xx"
string_triangle = string_triangle[1:]
print string_triangle