Python Python Basics All Together Now Branch and Loop

Christopher Hill
Christopher Hill
1,382 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

Ave Nurme
Ave Nurme
19,627 Points

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?