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 trial

Python Python Basics Functions and Looping Exception Flow

Daron Anderson
Daron Anderson
2,567 Points

Can someone please help me understand?

What is the explanation behind why when result = "test" + 5 ,
ADF Gets printed which is a string plus int

and when result = 5 + 5 , which is an int plus int ABEF is printed?

Daron Anderson
Daron Anderson
2,567 Points

Also have been trying to wrap my head around the operation order.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

In the first case, It's a given that "A" and "F" will print first and last, the question is with other print commands will run. In execution of the try, the first statement result = "test" + 5, will raise a TypeError because you the plus sign following a string is looking to concatenate other strings. When the 5 is parsed, it is not of the type str so it cannot be concatenated. When the TypeError is raised, the print("B") statement is skipped. Execution jumps to the except TypeError block, so the next print would be print("D"). Since the try block raised an error, the else block is also skipped. So it's "A", "D", "F"

In the second case, "A" and "F" will also print first and last. Now the plus sign is following an int so it expects addition. Since the second 5 can be added to the to the first 5, execution will move to the print("B") statement. This completes the try block and execution moves to the else block where the print("E") statement is run. So "A", "B", "E", "F"

Post back if you have more questions. Good luck!!

Daron Anderson
Daron Anderson
2,567 Points

Fantastic man I appreciate you for clarifying. :)