#๐ python beginner's question
21 messages ยท Page 1 of 1 (latest)
@cobalt valve
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.
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
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.
oh
(it's the other way around actually; also the next message repeats permission)
this will help you out https://realpython.com/python-lbyl-vs-eafp/
the point is so the program will keep running/not crash even if it runs into errors
however you need to get the error first in order to know which ones to "except"
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.
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