Python Python Basics All Together Now Gather Information

Ash Skelton
Ash Skelton
3,489 Points

Why reassign variable rather than combine?

Why would you reassign the variable to make it an int?

num_tickets = input("How many tickets would you like, {}  ".format(name))
num_tickets = int(num_tickets)

Would this not be cleaner?

num_tickets = int(input("How many tickets would you like, {}  ".format(name)))

Is there a reason to choose one method over the other in this scenario?

1 Answer

Steven Parker
Steven Parker
186,966 Points

Both versions are equivalent as long as no errors occur. Doing the steps separately might be useful for debugging.

For example, if the conversion should fail (as if the word "blue" was given for input), then in the first example "num_tickets" would sill have the input that caused the problem. But in the second example the input would not be saved anywhere.

Also, for the purposes of the videos, steps are often performed separately for clarity where in practice they can be consolidated to make the code more compact and efficient.

Ash Skelton
Ash Skelton
3,489 Points

Got it, thanks Steven!

In terms of your comment around steps being performed separately for clarity - this makes sense and is definitely useful to see how the flow should work, however, what may be just as useful is if the Treehouse teachers did a "clean up" session for the code maybe after the quizzes/challenges. That way, the student learns what exactly the code is doing in an easy to read flow, but also teaches you where you can consolidate some of the code and create efficiencies which would be beneficial to know in "real world" scenarios!

Thanks again

Steven Parker
Steven Parker
186,966 Points

Perhaps there's an opportunity for a "code optimization" course or workshop. You might send in a suggestion!