上下循环打印"-"和"*"[大师]
这个图案的第一行有5个短横线,后面跟着1颗星星;第二行有4个短横线,后面跟着3颗星星;第三行有3个短横线,后面跟着5颗星星,依此类推。最后一行没有短横线,只有11颗星星。
我想打印出这样的结果,但我不知道我的代码需要做什么修改。
-----*
----***
---*****
--*******
-*********
***********
def printing(dash, star):
for i in dash:
print("-")
for i in star:
print("*")
print(dash, star)
def main():
dash = 5
star = 1
while dash >=0:
printing(dash, star)
dash = dash-1
star = star+2
main()
6 个回答
0
你似乎想要用 for i in xrange(dash)
这个写法。可以参考这个链接了解更多内容:https://docs.python.org/2.7/tutorial/controlflow.html#for-statements
0
用Python的字符串重复和连接操作来构建你的输出,可能比用循环一个个打印字符要简单得多。如果你把一个字符串乘以一个整数,它会重复那个次数。而把两个字符串加在一起,就是把它们连接起来。
下面是一个简单的函数,可以生成你想要的输出:
def main():
for dashes in range(5, -1, -1): # dashes counts down from 5 to zero
stars = 1 + 2*(5 - dashes) # the number of stars is derived from dashes
print("-"*dashes + "*"*stars) # just one call to print per line
0
你不能直接对整数进行循环,你需要使用 range()
这个函数。
试试这个:
def printing(dash, star):
for i in range(dash):
print("-", end="")
for i in range(star):
print("*", end="")
print()
def main():
dash = 5
star = 1
while dash >=0:
printing(dash, star)
dash = dash-1
star = star+2
main()
输出结果:
-----*
----***
---*****
--*******
-*********
***********
2
你可能会对一个新算法感兴趣。试试这个。
s="-----*"
print(s)
while "-" in s:
s=s.replace("-*", "***")
print(s)
你会注意到 "-" in s
这一行。这只是用来检查字符串中是否有连字符(也就是“-”)。你可以这样做,因为字符串就像一个可以逐个查看的列表。你可以在里面添加任意数量的连字符。
5
你的代码哪里出问题了
for i in dash:
这行代码是想要遍历 dash
中的每一个元素 i
。但是你给它的是一个整数,而整数是不能被遍历的。
如果你想让它正常工作,应该改成 for i in range(dash)
。range(n)
会返回一个从 0 开始的 n 个整数的列表。这样你就可以循环 dash
次了。
更简单的方法
因为 Python 允许你用整数来乘字符串,这样可以有效地重复这个字符串,而且你可以通过简单地用 +
来连接它们,所以你可以用一种更简单的方法:
def printing(dash, star):
print '-'*dash + '*'*star