Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursion
#1
Hi, I'm working on a project for my class in which recursion MUST be use to display a corresponding amount of lines to a user's input. So far I have this code.

n = int(input("How many line to display? "))

def show_ast(n):

    if(n>0):

        show_ast(n-1)

    num = n;

    st = ""

    while(num>0):

        st +='*'

        num -= num

        print(st)

show_ast(n)
Wall Wall Wall Wall
I can't figure out why it only prints a single asterisk per line and doesn't add one subsequently.

Any help is appreciated. Thank you.

For anyone who viewed this, thank you. I was able to figure it out. If anything hopefully this can help someone in the future Cool Big Grin

n = int(input("How many line to display? "))

def show_ast(n):

    if(n>0):

        show_ast(n-1)

    num = n

    st = ""

    while(num>0):

        st += '*'*num

        num -= num

        print(st)

show_ast(n)
I just multiplied the number of asterisks in the while loop by the user input.
Reply
#2
The problem is that you are subtracting num from num on line 17, so your look only runs once, not num times. Although if you want a loop to run a certain number of times you should use a for loop:

def show_ast(n):
    if n > 0:
        show_ast(n - 1)
    text = ''
    for ast in range(n):
        text += '*'
    print(text)
But with the multiplication of the string that you figured out, you don't need any loop:

def show_ast()
    if n > 0:
        show_ast(n - 1)
    print('*' * n)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  GCF function w recursion and helper function(how do i fix this Recursion Error) hhydration 3 2,521 Oct-05-2020, 07:47 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020