Reputation: 31
I currently have created this code in python. The output is exactly what I want. (If you know of a better way to get it, I am open to hear). I want to know how I can combine my functions triangle and triangle2 into one main function. (My output is a sideways pyramid).
def triangle(n):
for x in range(n):
print ('*'*x)
n = n - 1
def triangle2(n):
for x2 in range(n):
print ('*'*n)
n = n - 1
height = int(input("Enter an odd number greater than 4: "))
triangle(height)
triangle2(height)
Upvotes: 1
Views: 2817
Reputation: 3067
If you always want to run them both in the order specified at the bottom I would do something like this:
def triangle(n):
for x in [y for y in range(n)] + [z for z in range(n, 0, -1)]:
print("*"*x)
height = int(input("Enter an odd number greater than 4: "))
triangle(height)
Upvotes: 0
Reputation: 1434
To keep it as close to your original Code as possible:
def triangle2(n):
for x2 in range(n):
print ('*'*n)
n = n - 1
def triangle(n):
for x in range(n):
print ('*'*x)
triangle2(n)
height = int(input("Enter an odd number greater than 4: "))
triangle(height)
You can just call your other function from the first one.
Upvotes: 0
Reputation: 1122502
Just put the two loops together into one function, but don't alter n
until the second loop (the first doesn't use it anyway):
def sideways_pyramid(n):
for x in range(n):
print('*' * x)
for x in range(n):
print('*' * n)
n = n - 1
You can avoid altering n
altogether by counting down with the range()
instead:
def sideways_pyramid(n):
for x in range(1, n):
print('*' * x)
for x in range(n, 0, -1):
print('*' * x)
The second loop counts down, starting at n
and ending at 1. I also start the first loop at 1, to not print an empty first line (0 times '*'
is an empty string)
Demo:
>>> def sideways_pyramid(n):
... for x in range(1, n):
... print ('*' * x)
... for x in range(n, 0, -1):
... print ('*' * x)
...
>>> sideways_pyramid(5)
*
**
***
****
*****
****
***
**
*
Upvotes: 1
Reputation: 359
def triangle(n):
for x in range(n):
print ('*'*x)
for x in range(n):
print ('*'*n)
n -= 1
height = int(input("Enter an odd number greater than 4: "))
triangle(height)
Upvotes: 0