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

Integer Coercion

Hello there,

Did anyone try putting a string as an answer for "How many tickets do you want?" to test if the coercion worked? I coerced the string in my code but I am, for some reason, receiving this error: ValueError: invalid literal for int() with base 10. I get this error if I use a string instead of an integer to answer the question. Here is my code:

TICKET_PRICE = 10

tickets_remaining = 100

Gather the user's name assign it to a new variable

user_name = input("Hello there! What is your first name? ")

Output how many tickets are remaining using the tickets_remaining variable

print(user_name , "there are only {} tickets remaining!".format (tickets_remaining))

Prompt the user by name and ask how many tickets they would like

number_of_tickets = input("How many tickets would you like to purchase, {}? ".format(user_name)) number_of_tickets = int(number_of_tickets)

Calculate the price (number of tickets multiplied by price) and assign it to a variable

amount_due = number_of_tickets * TICKET_PRICE

Output price to screen

print("That will be ${} please!".format(amount_due))

3 Answers

Steven Parker
Steven Parker
243,228 Points

The "int" function can only convert a string into a number if it contains digits, like 4 and 5. It cannot convert words (like "four" and "five") into numbers.

The error message you are seeing will be given for any string that is not composed purely of digits.

Thank you! This was driving me crazy. :)

Hi Kayla,

input() always returns a string, whatever value you provide it. If you type hello or 10, input will return either "hello" or "10".

int() will turn a string that looks like a integer (e.g., "10") into an int, and any string that doesn't look like an integer (e.g., "hello", "6.28") will return the error that you describe.

Are you getting this error message when entering values that look like integers?

Cheers

Alex

Thank you for responding! Yes, I'll put 'four' or 'five' etc and I still get the error.