Python try

whitehousechef·2025년 7월 1일

diff between try while and while try

while try

def run(self):
    while True:  # Loop continues even after exceptions
        try:
            # menu logic
        except ValueError:
            # Handle error, continue loop

Exceptions are caught per iteration - loop continues after handling

try while

def run(self):
    try:
        while True:  # Entire loop is protected
            # menu logic
    except KeyboardInterrupt:
        # Handle Ctrl+C, EXIT the loop

Exceptions are caught for the entire loop - loop exits after handling

so when to use which?

normally try while is for the main application run way cuz u wanna do the contrl + c exit flow, which while try cant cuz its infinite loop unless u break

try

try except is like try catch in java. except catches any exception

look at this else statment. It raises ValueError exception if number is not from 1 to 3.

def _update_booking(self, booking: Booking) -> str:
    user_input = self._get_user_input("Do you wish to 1. Cancel your booking 2. Update your booking "
                                      "3. Return to previous page? Press 1 or 2 or 3").strip()
    try:
        if user_input == "1":
            if self.select_cinema:
                result = self.select_cinema.cancel_booking(booking.booking_id)
                return "Booking cancelled successfully" if result else "Failed to cancel booking"
            else:
                return "No cinema selected"
        elif user_input == "2":
            if self.select_cinema:
                self.book_seats(booking) # This line implies re-booking, which cancels the old one first.
                                       # If you're updating, you should typically re-book *then* cancel the old ID,
                                       # or cancel the old ID *then* re-book. Your current order is cancel old, then book new.
                result = self.select_cinema.cancel_booking(booking.booking_id) # This seems redundant if book_seats handles the update
                return "Booking updated successfully" if result else "Failed to update booking"
            else:
                return "No cinema selected"
        elif user_input == "3":
            return "Returned to previous page"
        else: # This is the line in question
            raise ValueError("Invalid input")
    except ValueError:
        print("Please enter number 1 ~ 3")
        return "Invalid input"

but do we really need this else statment? Lets say we dont have that else and input is "abc". All the if statements are false so code just moves on to the next code after this try except block. Thus, this else statement catches any invalid inputs

but what about here?

try:
    num = int(input("Enter a number: ")) # Potential ValueError here
    result = 10 / num                  # Potential ZeroDivisionError here
    print(f"Result: {result}")
except ValueError:
    print("Invalid input. Please enter an integer.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e: # General catch for other unexpected errors
    print(f"An unexpected error occurred: {e}")
finally:
    print("Execution of try-except block completed.")

here the interpreter knows when to catch those exceptions without us needing to tell it when to catch that error.

why break/continue doesnt work in try

break/continue works in loops (while AND for), not in a function. Doesnt matter if the function has a try or not. As long as theres no loop, we cant use break/continue keyword

def _add_movie(self, theatre: Theatre):  # This is a FUNCTION, not a loop
    # ... code ...
    if len(user_input) != 3:
        break     # ❌ ERROR: No loop to break out of
        continue  # ❌ ERROR: No loop to continue

if u rly want a retry loop in _add_movie instead of returning back to run() function that called this _add_movie(), u can add a retry loop of while and add a continue

def _add_movie(self, theatre: Theatre):
    while True:  # Add retry loop
        print("Please define movie title and seating map:")
        user_input = input("> ").strip()
        
        if len(user_input.split()) != 3:
            print("Please enter [Title] [Row] [SeatsPerRow]")
            continue  # ✅ Now continue works - retry input
        
        try:
            total_rows = int(user_input.split()[1])
            # ... success! 
            break  # ✅ Now break works - exit retry loop
        except ValueError:
            print("Invalid format, try again")
            continue  # ✅ Retry input

0개의 댓글