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 Functions and Looping Functions

Creating a function for this script?

purchasing_item = input("Welcome to the $5 store what can I get for you? ")

if purchasing_item == "alcohol": age = int(input("How old are you? ")) if age >= 21: print("Great that would be $5") else: print("You need to be 21 or older to buy alchohol")

elif purchasing_item == "cigarettes": age = int(input("How old are you? ")) if age >= 18: print("Great that would be $5") else: print("You need to be 18 or older to buy cigarettes")

else: print("Great that would be $5")

I'm trying to turn this into a function so adding items to the list is easier than copy pasta but I'm getting thrown off by having multiple variables and inputs!

edit: I don't know how to attached a workspace so my code is formatted correctly

1 Answer

ivanbark
ivanbark
3,896 Points

purchasing_item = input("Welcome to the $5 store what can I get for you? ")

def functionName(item, minAge): if purchasing_item == item: if minAge > 0: age = int(input("How old are you? ")) if age >= minAge: print("Great that would be $5") else: print("You need to be {} or older to buy {}".format(minAge, item)) else: print("Great that would be $5")

functionName("alcohol", 21) functionName("ciggerettes", 18) functionName("milk", 0)

Look at the code above. You can make a function out of the code you made for the products. You can just add multiple variables within the brackets as shown above. I hope this helps. Good luck!