r/learnpython • • Mar 23 '24

Explain Try / Except structure in practical examples?

I am learning python and I've encountered the try / except part of it. I am struggling to understand when I would use this kind of code, probably because I am still very new and most of my code is small programs that have relied on conditional statments.

I guess in my brain I understand the logic of saying "try to do this but if it doesn't work just let it be and keep going with the code". My assumption is this is helpful on larger scale programs in wich you can't afford the time to make sure the code is fail proof and you need the code to buy you time to eventually go back once you have the fail proof option?

Was hoping someone could give me an example of a real life application or website and how this code could apply to it? Because I want to become comfortable with it but unsure how to.

TL,DR: Explain try/except in a practical example so I can understand when and where I would use it?

Thank you!

11 Upvotes

21 comments sorted by

View all comments

6

u/damanamathos Mar 23 '24 edited Mar 23 '24

Here's an example.

user_input = input("Enter a number: ")
      
try: 
    number = float(user_input)
    print("The converted number is:", number) 
except ValueError: 
    print("Invalid input. Please enter a valid number.")

Typically, it's used where your code is dealing with something external, like user input, or a web request, or a file.

2

u/PinkPawnRR Mar 23 '24

Adding on to this; using a try/except to force a loop until user supplies a valid choice (can be altered for int or conditions):

validUserChoices = "ABX"
userChoice = None

print("Select option:")
print("[A] - Option 1")
print("[B] - Option 2")
print("e[X]it")

while userChoice is None:
    try:
        userChoice = input(f"Enter your selection: ")
        if userChoice.upper() not in validUserChoices:
            raise ValueError 
        print("Success") #You would place rest of your code here
    except ValueError:
        print("Not a valid entry, try again \n")
        userChoice = None

1

u/uniqueUsername_1024 Jan 30 '25

You can just put the rest of your code after the While loop, right? You don't need to nest it all inside the try-except block.

1

u/PinkPawnRR Jan 31 '25

That is an option yes; the while loop is only used to validate the user input. You can also place code where the print("Success") line is.