简体   繁体   中英

printing a right angle and isosceles triangle

I'm trying to print a right angle and isosceles triangle from one inputted odd number. I can get it to print one or the other but when I try to print both it prints something like this:

  ****
**********
    ***
***********
     **
************
      *
*************

my code so far is:

row = int(input("enter row:"))
if row %2 ==0 or row<=0:
    print("enter an odd positive number")
else:
    for i in range(row) :
        #print("right angle",end="")
        #print("\n")
        print (" "*i+"*"*(row-i))
        
#print("isoscoles")
#print (" "*i+"*"*(row+i))

and if I put in

print ("right angle "*i+"*"*(row-i))

I get

right angle right angle right angle right angle ***
right angle right angle right angle right angle right angle **
right angle right angle right angle right angle right angle right angle *

What I'm trying to do is:

Enter an odd positive integer: 7

Right-Angled Triangle:
*******
 ******
  *****
   ****
    ***
     **
      *

Isosceles Triangle:
   *
  ***
 *****
*******

I'd appreciate some help as my head is melted XD

This code could work:

# loop till a valid answer is given
while True:
    # this may raise ValueError if not a valid integer; optionally
    # add try ... except ...
    n = int(input('Enter an odd positive integer:'))

    if n % 2 != 0 and n > 0:
        # exit while loop
        break

print()
print('Right-Angled Triangle')
# build and print a string with decreasing amount of stars
for i in range(n):
    print('*' * (n - i))
# build and print a string with decreasing amount of stars, but also
# print an increasing amount of space in front
for i in range(n):
    print(' ' * i, '*' * (n - i), sep='')

print()
print('Isosceles Triangle')
# loop starting at 1 increasing 2 at a time
for i in range(1, n+1, 2):
    print(' ' * ((n - i) // 2), '*' * i, sep='')

Output:

Enter an odd positive integer:7

Right-Angled Triangle
*******
******
*****
****
***
**
*
*******
 ******
  *****
   ****
    ***
     **
      *

Isosceles Triangle
   *
  ***
 *****
*******

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM