<p>这是剧本。我假设多个输入字符意味着多个输出三角形。另外,高度:0表示每个三角形中的零线。</p>
<p>我今天学到的一件棘手的事情是<code>int("20.0")</code>不会转换为20;它会引发一个异常。代码通过先转换为float来解决这个问题。</p>
<pre><code>#!/usr/bin/python3
def triangles(characters, height):
# We could call int(height) here except that int("20.0") for example raises
# an error even though there is a pretty clear integer value. To get around
# that, attempt to convert to float first.
try:
lines = float(height)
except ValueError:
# If we raise here, the error is like: cannot convert to float. That's
# confusing, so we let it go.
lines = height
# If the value can't be converted to int, this raises an error like: cannot
# convert to int. If it had already converted to float, this rounds down.
lines = int(lines)
for character in characters:
# Loop will execute no times if lines==0, once if lines==1 and so on.
for line in range(1, lines + 1):
print(str(character) * line)
print("")
if __name__ == '__main__':
try:
triangles(input("Enter characters: "), input("Enter height: "))
except ValueError as error:
print("Couldn't print triangles:", error)
</code></pre>
<p>编辑:添加了示例输出。</p>
<pre><code>$ ./triangles.py
Enter characters: jk
Enter height: 8
j
jj
jjj
jjjj
jjjjj
jjjjjj
jjjjjjj
jjjjjjjj
k
kk
kkk
kkkk
kkkkk
kkkkkk
kkkkkkk
kkkkkkkk
$ ./triangles.py
Enter characters: .
Enter height: 3.0
.
..
...
$ ./triangles.py
Enter characters: f
Enter height: 3.7
f
ff
fff
$ ./triangles.py
Enter characters: duff
Enter height: duff
Couldn't print triangles: invalid literal for int() with base 10: 'duff'
</code></pre>