1

I have successfully created a code to print a horizontally flipped triangle using a while loop. Now although it works, I was wondering if i could simplify this i.e. without using a "store" variable. But i want to keep it using a while loop

Current code is:

myLen = int(input("Enter the number of rows: "))
while myLen < 1 or myLen> 40:
      print("The number of rows must be greater than 1 and less than 40")
      myLen = int(input("Enter the number of rows: "))

myNewLen=1
store=myLen
while myNewLen <=store:
      print((" "*(myLen-1))+"*" * myNewLen)
      myNewLen=myNewLen+1
      myLen=myLen-1

Which will print out a result of:

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

I was wondering how i could simplify this code for efficiency.

4
  • myLen is undefined Commented Oct 27, 2016 at 16:40
  • 2
    Also for bug free optimization questions maybe consider posting here: codereview.stackexchange.com Commented Oct 27, 2016 at 16:40
  • Sorry i didnt include the top part of my code, let me edit Commented Oct 27, 2016 at 16:41
  • Do you have to use a while loop? @Xrin Commented Oct 27, 2016 at 16:45

1 Answer 1

2

Essentially, you still need to keep track of which row you're on and just do a little more math to see how many *'s and " "'s there should be. Hope this helps.

myLen = 5
i = 1
while myLen >= i:
    print( ("*" * i).rjust(myLen) )
    i += 1
Sign up to request clarification or add additional context in comments.

2 Comments

Ah i see, this makes a lot of sense, simple and clear to the point. Thanks!
Personal preference perhaps, but I think it'd be even neater to use rjust - the print line would then become print(("*" * i).rjust(myLen))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.