Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

help please! How do I create a loop inside of an existing loop?

I want to create a loop inside of the loop, so after the error message pop up, the same question raise again until answer is correct, instead of starting answering all the questions again from beginning.,

Here is my code:

TICKET_PRICE = 10
SERVICE_CHARGE = 2

tickets_remaining = 100

def calculate_price(number_of_tickets):
  return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE

while tickets_remaining >= 1 : 
      print("\n There are {} tickets remaining.".format(tickets_remaining))
      name = input("\n What is your name?  ")
      try:
        num_tickets = input("How many tickets would you like, {}?  ".format(name))
        if all(char.isdigit() for char in num_tickets) == False:
          raise ValueError("input is not valid number. ")
        else:
          num_tickets = int(num_tickets)
        if num_tickets > tickets_remaining:
           raise ValueError ("{}, please insert the good number! No more than {} tickets available at this moment..\n".format(name,tickets_remaining))
      except ValueError as err :
          print("Oh no, you are wrong! {} ".format(err))
      else:
        amount_due = calculate_price(num_tickets)
        print("The total due is ${}".format(amount_due))
      try:
        procedure = input("{}, do you want to procede ? Please print y/n  ".format(name))
        if (procedure.lower() == "y" or procedure.lower() == "n") == False :
          raise ValueError ("Please type y/n. Thank you!")
        else:
          if procedure.lower() == "y" : 
            print("SOLD") 
            tickets_remaining -= num_tickets
            print("{} tickets remaining".format(tickets_remaining))
          else:
            print("You will regret, this is a bad choice!")
      except ValueError as err :
        print('{}'.format(err))
      print("Have a blessed day {}".format(name))

2 Answers

Steven Parker
Steven Parker
243,658 Points

There's nothing special about a loop inside another loop, except an extra level of indenting:

x = 3
while x:
    print("outer loop")
    y = 2
    while y:
        print("inner loop")
        y -= 1
    x -= 1

Thank you, I got it!