#๐Ÿ”’ python beginner's question

21 messages ยท Page 1 of 1 (latest)

cobalt valve
#

can someone explain the necessity of using 'try' and exception commands? Because right now, I am thinking that these commands can just be altered by while loop or 'if' statement (such as if non integer / input == zero, print something like that)

dusk tideBOT
#

@cobalt valve

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

meager skiff
#

if you do "if non integer" then you can not instantly cast the input to an int. but yes for validating user input try-except is not necessary you can get the input as a string do all validation checks and then convert it and work with it

#

but there are things where it could be that an error occurs but you do not know if the error occurs. like when you want to open a file but it could be that the programme has no permission to open it or it could not exists so you need to handle that

lunar lark
#

In Python, there exists the adage, "It's easier to ask for permission than forgiveness."

#

try/except is asking permission, if / else is asking permission.

#

For applicable situations, the code you write when applying a try / except pattern will often be more concise than applying an if / else pattern.

cobalt valve
#

oh

oblique wasp
white coral
tender yacht
#

however you need to get the error first in order to know which ones to "except"

lunar lark
#
things = 'Apples', 'Oranges', 'Pears'
index = 9001
if index < len(things):  # Doesn't even cover all IndexError cases!
    print(things[index])
else:
    print('No.')```
vs
```py
things = 'Apples', 'Oranges', 'Pears'
index = 9001
try:
    print(things[index])
except IndexError:
    print('No.')```
#

The Look Before You Leap pattern involves writing tests, which can get involved.

#

The Asking Forgiveness pattern lets you just specify the kinds of exceptions you expect could happen.

cobalt valve
#

ohhh

#

I see

#

thank you guys

dusk tideBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

๐Ÿ”’ python beginner's question