def main():
n = int(input("How many lines to display? "))
for i in range(n):
print("*" * i)
input("Press the <Enter> Key to quit")
main()
I somehow need to make this recursive. But this is suck a simple loop I'm not sure how I could make it recursive. Any advice is appreciated.
CodePudding user response:
Hoping you can learn by seeing:
def triangle(n):
if n <= 1:
return ['']
return [*triangle(n - 1), '*' * n] # or triangle(n - 1) ['*' * n]
n = 5
print('\n'.join(triangle(n)))
#
# **
# ***
# ****
# *****
The function returns a list of lines, not a single string (since concatenating strings at every step is not recommended). Hence you need to join
them with '\n'
, the newline character, and print it.
I believe the above is a very standard recursive function; there is a "base case" (i.e., when the recursion ends; here, it is when n <= 1
), and the body, where recursively calls itself (triangle(n - 1)
), and then a return
.
For a one-liner, you could use generator comprehension:
print('\n'.join('*' * x for x in range(n)))
CodePudding user response:
One way of doing it is to tell the function what iteration you're on and what the total iterations you want are. The function then prints a line, and then calls the function for the next iteration. So, for instance, if n=3, you first call the function for n=3 and i=0 to get the first iteration, then the function calls itself for n=3 and i =1 for the next iteration, which calls itself for n =3 and i=2.
def display_rows(n,i):
if i == n:
return
print("*" * i)
display_rows(n, i 1)
You can simplify this by combining the two variables n and i into one; define u = n-i, and when u gets to zero, stop.
def display_rows(u):
if u == 0:
return
display_rows(u-1)
print("*" * u)
I changed the order of the print("*" * u)
and display_rows(u)
lines because u is going "backwards" (from n to 0), so you need to do the recursion call before printing. This does make it a bit less tail-recursiony, but given that you asked this question in the first place, you probably aren't familiar with tail recursion anyway.
CodePudding user response:
you need to wrapper a recurisive loop out of for loop.
And you need better to check input_line is numeric to exclude bad input.
As input will return empty str to it, you can check if input_line
is empty to exit while
loop by break
def main():
while True:
input_line = input("How many lines to display? ")
if input_line.isnumeric():
for i in range(int(input_line)):
print("*" * i)
elif input_line == '':
break
else:
print("wrong input")
main()
CodePudding user response:
It's not the prettiest way to do this but -> Here is an example with input and recursion:
def printy(n): return f"{'*'*n}\n{printy(n-1)}" if n > 0 else ''
def main():
x = printy(int(n) if (n:=input("How many lines to display? ")).isdigit() else 0)
if x:
print(x)
main()
print('Press the <Enter> Key to quit')
main()