Print Line of N Stars Recursively

Print n stars in a line using recursion.

IntermediatePhase 3 - Level 3: Pattern RecursionExample 1 of 10
print-line-of-n-stars-recursively.py
1def print_stars(n):
2 # Base case
3 if n == 0:
4 return
5
6 # Recursive case
7 print("*", end="")
8 print_stars(n - 1)
9
10# Test
11n = int(input("Enter n: "))
12print_stars(n)
13print()

Output

Enter n: 5
*****

What's going on

Print one star, then recurse for n-1 stars.

Key Concepts:

Base case: n == 0, return
Print one star
Recurse with n-1