Draw an M-shaped pattern with nested loops

前端 未结 4 1148
慢半拍i
慢半拍i 2020-12-12 02:11

I just started Python 2.7 very recently, but I\'m stuck at this a problem:

Make a program that prints an \"M\" pattern of asterisks. The user shall in

4条回答
  •  情歌与酒
    2020-12-12 02:56

    Limitation: Enter only old number greater than 3

    Logic:

    1. Get input from user by raw_input().
    2. Get number of space count by subtracting 2 from the user input. e.g. (i) for user input is 3 only first line have 1 space, (ii) for input 5--> first line have space 3 and second line have space 1.
    3. Run for loop n time where n is user value.
    4. If space count is greater then 0 then create print_line where add space value according to space count in the middle of string and * at start and end according to for loop count.
    5. If space count is less then 0 then print string to * according to user value.

    Code:

    no = int (raw_input("Enter a number: "))
    space_no = no - 2
    print_line = "*"*no
    for i in xrange(1,no+1):
        if space_no>0:
            print_line_n = "*"*i+" "*space_no+"*"*i
            space_no -=2
            print print_line_n
        else:
            print print_line
    

    output:

    vivek@vivek:~/Desktop/stackoverflow$ python 9.py 
    Enter a number: 3
    * *
    ***
    ***
    vivek@vivek:~/Desktop/stackoverflow$ python 9.py 
    Enter a number: 5
    *   *
    ** **
    *****
    *****
    *****
    vivek@vivek:~/Desktop/stackoverflow$ python 9.py 
    Enter a number: 9
    *       *
    **     **
    ***   ***
    **** ****
    *********
    *********
    *********
    *********
    *********
    vivek@vivek:~/Desktop/stackoverflow$ 
    

提交回复
热议问题