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 trialGregory Johnson
3,367 PointsI'm a little lost on what try and except do, it seemed like it was working with out it
What's the purpose of try and except
5 Answers
Chris Freeman
Treehouse Moderator 68,457 PointsThe try
statement allows you to run code where the outcome is uncertain. The is usually used in cases where you are dealing with results outside of you control (user input, working OS resources) or to verify the code functionality is acceptable. The except
statement defines what to do in case of various errors are actually seen.
In other languages, the onus is on the programmer to protect against bad conditions explicitly, such as checking if a denominator is not zero before dividing. In python, the philosophy is "Easier to ask for forgiveness than permission" EAPF. This is contrasted to the "Look before you leap" LBYL philosophy.
Gregory Johnson
3,367 Pointsguess = int(input("Guesss a number between 1 and 10"))
doesn't this statement say that only a number can be used...or was the try and except used as a way to get feedback?
[MOD: added ```python formatting -cf]
Chris Freeman
Treehouse Moderator 68,457 PointsThis says "get input from user then convert to integer then a sign to the variable guess
". If the user enters something that cannot be converted to an integer then a ValueError will be raised. Without a try/except statement to catch the ValueError the program will Halt
Gregory Johnson
3,367 PointsI see, thank you!
Benito Thompson
1,650 PointsApparently you cannot put "print(...... .format(guess))" underneath the except ValueError like you did in the video, because if you get a ValueError, it means that the guess was not assigned to the variable in the first place so it is impossible to call it. When I put print("That isn't a number!") then it worked.
I'm not sure if what I said made sense. But someone tell me if that is right or if I missed something. Thank you!
Chris Freeman
Treehouse Moderator 68,457 PointsYou've got it correct! See my new comment added above.
Benito Thompson
1,650 PointsOh! I see! Thank you Chris!
Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsIn the example of converting input to an integer instead of doing it all in one line:
Use the
try
to capture the specific issue that it might not convert to and integer: