Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics All Together Now Branch and Loop

Christopher Hill
Christopher Hill
1,425 Points

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?