我是编程新手,我有一项任务,需要我建立一个"星星"在它下面有一行6,一行是5,然后是另一行6,依此类推。我需要使用嵌套循环,但似乎无法超越第一行。 以下是我到目前为止的情况:
def main():
# Setup accumulator and variable
rows = 0
stars = 0
# Get user inputs
rows = int(input("How many rows for this design?\n"))
stars = int(input("How many stars on the first row?\n"))
# Print i
for i in range(stars):
print("*", end="")
break
第二次尝试:
def main():
# Get user inputs
rows = int(input("How many rows for this design?\n"))
stars = int(input("How many stars on the first row?\n"))
# Print i
for i in range(stars):
for j in range(rows):
print(stars*"*")
print(rows*"*")
break
答案 0 :(得分:1)
如果我理解正确,您可以使用modulo
和stars-1
来替换输出:
rows = int(input("How many rows for this design?\n"))
stars = int(input("How many stars on the first row?\n"))
for i in range(rows):
if i % 2 == 0:
print(stars * "*")
else:
print ((stars-1) * "*")
对于9行和6星,它输出:
******
*****
******
*****
******
*****
******
*****
******
if i % 2 == 0:
会为每个i
输出6颗星,否则我们会打印stars-1
颗星。
使用嵌套for循环:
for i in range(rows):
s = ""
for j in range(stars):
s += "*"
if i % 2 == 0:
print(s)
else:
print(s[:-1])
答案 1 :(得分:0)
这对我来说听起来不像是一个矩形,但我这样做的方法是使用一个条件表达式,当行号除以2时,根据余数选择每行的长度。
看起来像这样
rows = int(input("Number of rows for this design: "))
stars = int(input("Number of stars on the first row: "))
for row in range(rows):
len = stars if row % 2 == 0 else stars - 1
print '*' * len
<强>输出强>
Number of rows for this design: 9
Number of stars on the first row: 6
******
*****
******
*****
******
*****
******
*****
******