python矩形的星号?

时间:2014-09-14 00:20:07

标签: python

我是编程新手,我有一项任务,需要我建立一个"星星"在它下面有一行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

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您可以使用modulostars-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
******
*****
******
*****
******
*****
******
*****
******