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

Ben Crocker
Ben Crocker
2,756 Points

Converting string input into an int

I'm programming a personal store-type app (just for fun and practice) with items and then a price for those items as a int that looks something like this:

sword = 20

I can get the user to select what they want to buy, but then it comes up as a string, how do I get the user's input, e.g. sword, to turn into 20 so I can calculate the price?

2 Answers

Steven Parker
Steven Parker
231,275 Points

It sounds like you might store a list (perhaps a dictionary object) of items and prices, and when you get input look for a matching one which you could get the associated price from.

Which courses are you taking? There are examples of things very much like this in the course exercises.

Ben Crocker
Ben Crocker
2,756 Points

I'm still up to the Beginning Python course

Steven Parker
Steven Parker
231,275 Points

I don't recall if that one covers dictionaries, but you'll find out about them shortly if you're taking the track.

But here's a preview:

items = {"sword": 20, "knife": 10, "boots": 7}  # I made up some extra items here
choice = input("What would you like? ")
price = items[choice]
print("The {} price today is ${}".format(choice, price))
Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Ben! Any input coming in from the user will always be a string, and this is true across every programming language I've come across. In Python, you can convert the input to an integer or float with the int() or float() methods.

number_string = "4"
number = int(number_string)
print(number + 10)
# the last line will print 14

Note, though, that if the user enters something that can not be converted to a number like "Treehouse", then a ValueError will be raised.

Hope this helps! :sparkles: