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 All Together Now Branch and Loop

I'm confused about num_tickets = int(num_tickets)

I'm confused with how int(num_tickets) plays a part, why do we assign num_tickets to int(num_tickets)?

I don't understand how the in() function plays into the code.

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

2 Answers

Hi Christopher

EDIT: Edited the examples a bit...too many 5's may be confusing :-)

The int() is important for the arithmetic calculation which takes place in the program where we calculate amount_due. By default input() is a string and we need to convert the string into an int to make the calculations.

Here are two examples for you.

In this first example we convert the string into an int:

TICKET_PRICE = 3

num_tickets = input("How many tickets would you like?   ")
num_tickets = int(num_tickets)
amount_due = num_tickets * TICKET_PRICE

print(f'\nYou wished for {num_tickets} tickets.')
print(f'The total for this is {amount_due} dollars.')

"""
OUTPUT:

How many tickets would you like?   5

You wished for 5 tickets.
The total for this is 15 dollars.
"""

In this second example we do not make the conversion:

TICKET_PRICE = 3

num_tickets = input("How many tickets would you like?   ")
amount_due = num_tickets * TICKET_PRICE

print(f'\nYou wished for {num_tickets} tickets.')
print(f'The total for this is {amount_due} dollars.')

"""
OUTPUT:

How many tickets would you like?   5

You wished for 5 tickets.
The total for this is 555 dollars.
"""

As you can see the total in both examples differs.

Here is a shorter example for you:

example_int = 3
example_string = 'aaa'

print(example_int * 5)
print(example_string * 5)

"""
OUTPUT:

15
aaaaaaaaaaaaaaa
"""

EDIT: In the last example there are 5 blocks of the string 'aaa' (aaa aaa aaa aaa aaa) since this is the behaviour when you multiply strings with a number. In this case we multiplied 'aaa' * 5.

Does this make things clearer for you?

This helps a lot, thank you.