Slicing a dictionary to print specific information - python-3.x

This is part of something larger i'm working on but i needed to figure out how to do it for this section in order to move on.
Note: This is not homework, only a personal project.
Roxanne = {'Location': 'Rustboro City', 'Type': 'Rock',
'Pokemon Used': 'Geodude: Lvl 12, Geodude: Lvl 12, Nosepass: Lvl 15'}
user = input("What would you like to learn about: Gym Leaders, Current Team, Natures, or Evolution ")
if user == 'Gym Leaders' or 'gym leaders':
response = input('Who would you like to learn about? '
'Roxanne, Brawly, Wattson, Flannery, Norman, Winona, The Twins, or Juan? ')
if response == 'Roxanne' or 'roxanne':
ask = input('What would you like to know about? Location, Type, Pokemon Used ')
if ask == 'Location' or 'location':
# i need to print the location part of the Roxanne dictionary here, i.e. 'Rustboro City'
I'm just testing to see if I should just print the entire 'Roxanne' dictionary based on user input, or if I should print individual info from it, so that a user can find specific information.
Finally, the only python experience I have is the introductory course I'm taking in Uni right now, so nothing too difficult or complicated. The challenge I set myself was to stay within the boundaries of the course.

Related

How to change an input() to lower case?

I'm new to python and trying my best to learn. At this moment I'm following to program along with YouTube. But I got stuck with this piece of code where I'm trying to change user input to lowercase and comparing it to a list to see if item is available or not. And ever time I ran code I get Not available. Here is the code:
stock = ['Keyboard', 'Mouse', 'Headphones', 'Monitor']
productName = input('Which product would you like to look up:').lower()
if productName in stock
print('Available')
else:
print('Not Available')
- List item
Change your stock array to be all lowercase, like so:
stock = ['keyboard', 'mouse', 'headphones', 'monitor']
Because you modify the user input to be lowercase, no matter what, and the stock items in the array are capitalized, no matter what, they will never match in your if statement. String comparison in Python is case sensitive (as it is in nearly every programming language).

Python for loops: applying a value to one index and another one to the other indexes

I am trying to create a program that will allow a game reviewer to input what categories the game falls under, it should then print the appropriate category with a checkbox, and the other categories with a blank box.
I have managed to write a for loop that prints out the correct category with the checkbox, but am struggling to loop through the rest of the values to print them with a blank box.
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
print ("===[ Audience: ]===")
for i in audience_list: #cycles through the list of audience options
if i == audience_list[audience-1]: #for the audience option that was selected, print it with a check box
print ("%s %s" % (yes, audience_list[audience-1]))
else: #for the audience options weren't selected, print them with a blank checkbox
print ("%s %s" % (no, audience_list))
Is there a way for me to print every index other than the one that has been assigned to the 'audience' variable?
I'm using Python 3.2.3.
Just print i! If you print audience_list, you will output the whole list of every element; whereas i is the one you are currently checking.
for i in audience_list:
if i == audience_list[audience-1]:
print ("%s %s" % (yes, audience_list[audience-1]))
else:
print ("%s %s" % (no, i))
and a test (having entered 3) gives a neat output of:
☐ Kids
☐ Everyone
☑ Casual Players
☐ Pro Players
Consider enumerating the list items:
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
choice = 3 # Casual.
for (index, name) in enumerate(audience_list, start=1):
if index == choice:
print("[X] " + name)
else:
print("[ ] " + name)
Output:
[ ] Kids
[ ] Everyone
[X] Casual Players
[ ] Pro Players
I'm going to answer this because I feel the other answers haven't answered your underlying question.
Here's the code I propose:
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
selection = audience_list[audience-1]
print ("===[ Audience: ]===")
for option in audience_list: #cycles through the list of audience options
print ("%s %s" % (yes if option == selection else no, option))
There are two major changes here.
First, I created the variable selection, outside of your for loop. This cleans up your loop and is closer to what you're doing. You don't care about the number, you care about what the user selected.
Second, I put the if part of your for loop into the print statement. This is to highlight something important: the only difference you want in each iteration of your loop is whether or not the box is checked. Either way, you want to print the element of audience_list. This print statement shows that. You either print an empty box or a checked one, and either way, you print the element.
Note that some confusion may have come from your for i..., because typically an i like that is an int. Consequently, I changed my for loop iterator to be named option, which is much more clearly a string.
I think your main question gets addressed by this. You could have printed audience_list[audience-1] in both your yes and no lines, or you could more simply have printed i in both of your lines. (Or, as per Joe's code at this time, you could have made one audience_list[audience-1] and one i, since as it's written, they're both the same.) But since you're looping through all the options, other than the box, you should print the same option string, whether it's selected or not.
Note, in my comments with Joe, I mentioned that you could squeeze the for loop and below all on to one line. Then your code would look like this:
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
selection = audience_list[audience-1]
print ("===[ Audience: ]===")
_ = list(map(lambda o: print ( "%s %s" % (yes if o == selection else no, o)), audience_list))
This is logically equivalent, but a lot harder to read, so while it's fun to do, I wouldn't recommend it. (Briefly: map takes a function, in this case, the unnamed lambda function, and runs every member of the iterator audience_list through that function. list is necessary to make the map object actually do the processing, and the _ = is just to tell any other readers that we know we're throwing away the list.)
As Joe mentions, there is a less ugly way to do it that doesn't require mapping. The last line could be:
_ = [print ( "%s %s" % (yes if o == selection else no, o)) for o in audience_list]
This is slightly less confusing, since it removes the list(map( noise.
These are pretty much all functionally equivalent. And while it's fun to toss things in to a single line, don't get lost in that. Readability, maintainability and the ability to easily debug are the most critical.

trying to create a fill in the blank quiz in python

I have to make a fill in the blank quiz for my online class but I seem to be stuck, and am having trouble finding out why I'm stuck. Any advice would be great, thanks! this is my code so far... When I run the code it gets to the point of asking the first question and is looking for an answer but when I put it in it gives me the "not quite, please try again" prompt so am I not calling the answers right?
print ('Welcome to my computer programming Quiz, in this quiz you will be
asked to select from three difficulty levels, easy, medium, and hard. Each
the level contains 4 - 5 fill in the blank questions')
print ('')
print ('Your score at the end will be based on how many correct answers you
get compared to the number of guesses you take')
print ('')
# opening introduction to the Quiz
level=None
while level not in ['easy', 'medium', 'hard']:
level = input ('Please select a difficulty (easy, medium, or hard):').lower()
# This is where the difficulty is chosen, this is also is the reason I couldn't get my
# code to open until I did some searching around the internet and found that
# raw_input had to be replaced with input in newer versions of python. Also, I found
# that adding .lower() makes the user's input lower case so that it fits with the
# potential answers.
guesses, score = 0, 0
# this is where the number of guesses and the number of right answers will be collected
# and then shown to the user at the end
easy_questions = ['When you give a computer an instruction, its called
giving a computer a _____.',
'The _____ of a computer language is the set of rules that
defines the combination of symbols that are considered to be a correctly
structured document or fragment in that language.',
'A _____ is a value, one that can change based on conditions.',
'One piece of a larger group is called a _____ in computer
programming.',
'_____ are made up of elements, and are enclosed in square brackets.']
medium_questions = ['A _____ starts with the keyword def followed by the its name.',
'A _____ is a character that represents an action, such as x representing multiplication.',
'A _____ is a set of coded instructions that tell a computer how to run a program or calculation.',
'A _____ is traditionally a sequence of characters either as a literal constant or as some kind of variables.',
'An expression inside brackets is called the _____ and must be an integer value.']
hard_questions = ['A sequence of instructions that is continually repeated until a certain condition is reached, is called a _____ function.',
'A control flow statement that allows code to be executed repeatedly based on a true/false statement is called a _____ loop.',
'This is a common thing in programming when a variable is defined and then redefined the variable has gone through a _____.',
'_____ refers to the situation where the same memory location can be accessed using different names']
# The first thing I tried was having all the questions and then all of the answers
# together in two big lists bc of some code I saw online while researching how to
# do this project but couldn't figure out how to make that code work so I started
# over and tried this way with longer code but code I thought I could make work.
easy_answers = ['command', 'syntax', 'variable', 'element', 'lists']
medium_answers = ['function', 'operator', 'procedure', 'string', 'index']
hard_answers = ['loop', 'while', 'mutation', 'aliasing']
if level == 'easy':
questions = easy_questions
answers = easy_answers
elif level == 'medium':
questions = medium_questions
answers = medium_answers
elif level == 'hard':
questions = hard_questions
answers = hard_answers
# this is how I bet thought to get the the right questions and answers to be called up.
number_of_questions = 5
question_number = 0
def check_answer(user_answer, questions, answers):
if user_answer == answers:
print ('')
print ('Correct!')
score = + 1
guesses = + 1
question_number = + 1
# this will increase the score and guesses by one and move the quiz on to
# the next question.
else:
print ('')
print ('Not quite, please try again')
guesses = + 1
# this will only increase the guesses by one, and give the user another
# chance to answer the same question again.
while question_number < number_of_questions:
questions = questions[question_number]
user_answer = answers[question_number]
print('')
user_answer = input (questions + ': ').lower()
# Prompts the user to answer the fill in the blank question.
print (check_answer(user_answer, questions, answers))
# this is where im also having a lot of trouble, ive done some research online and this
# is what i was told to use but it doesn't seem to be working.
print ('')
print ('Congratulations, you have completed the ' + str(level) + ' level, with a score of ' + str(score) + ' out of ' + str(guesses) + ' guesses')
Well the problem seems to be very trivial. When you check if the answer is correct or not in the check_answer with the code line below:
if user_answer == answers:
you're answers is an array containing all the answers while the user_answer is the string that the user has typed. Hence, when you type the first answer as "command" is tries to match the string "command" to an array containing a few strings. which is definitely not gonna match.
use the below code line to solve it:
if user_answer in answers:

program to look up price in dictionary

I am having issues with creating this program I don't know whether I should use elif or something else.
Here is the question: In the cell below, use the try/except control structure to create a program which looks up a price in a dictionary.
shop_prices = {
'eggs': 1.99,
'milk': 0.99,
'ham': 4.99,
}
# take two inputs - what the customer wants, and how many of the items they want
# always greet the customer
# see if they sell the item and calculate the price
# otherwise say "We don't sell XXX", where XXX is the item
# always say goodbye to the customer
This may be what you're looking for. It asks what you want, and if it isn't available, it asks again. After that, it asks you how many of that item you want, and if that input is valid, it prints out the cost and exits.
shop_prices = { 'eggs': 1.99, 'milk': 0.99, 'ham': 4.99, }
request = input("Hello, what would you like?\n")
while request not in shop_prices.keys():
request = input("That item isn't currently available, please choose another item.\n")
while True:
try:
numof = int(input("How many of that item would you like?\n"))
break
except ValueError:
print("That isn't an integer, please enter an integer.\n")
print("That will be $"+str(numof*shop_prices[request])+". Thank you for shopping here today.\n")

In python, how do you loop a dictionary but keep the changes made to it

So basically im new to python and programming in general. I was wondering say you have a situation where you have a dictionary and are asking the user if they want to add or delete terms in the dictionary. So I know how to add or delete the term in dictionaries but how do "save" that data for the next time the program starts. Basically, if the user added a word to the dictionary and then I asked them if they wanted to return to the main menu using a while loop, how would you make it so the word they added is now permanently in the dictionary when he returns to the menu and starts the program over?
Here is what I had. Mind you I'm a beginner and so if it looks weird, then sorry...lol....nothing serious:
loop=None
while True:
#The initial dictionary
things={"house":"a place where you live",
"computer":"you use to do lots of stuff",
"iPod":"mp3 player",
"TV":"watch shows on it",
"bed":"where you sleep",
"wii":"a game system",
"pizza":"food"}
#Menu
print("""
Welcome to the Dictionary of Things
Choose your preference:
0-Quit
1-Look up a Term
2-Add a Term
3-Redefine a Term
4-Delete a Term
""")
choice=input("\nWhat do you want to do?: ")
elif choice=="2": #Adds a term for the user
term=input("What term do you want to add? ")
if term not in things:
definition=input("Whats the definition? ")
things[term]=definition #adds the term to the dictionary
print(term,"has been added to the dictionary")
menu=input("""
Would you like to go back to the menu?
Yes(Y) or No(N): """)
if menu=="Y":
loop=None ----->#Ok so if they want to go back to the menu the program should remember what they added
elif menu=="N":
break
Update:
Your problem is that you redefine the dictionary at the start of each loop. Move the start definition of the dictionary to before the While loop, and you are in business.
Dictionaries and lists are mutable objects. Hence, if it is modified in a function, it stays modified where it was called too:
def main_function():
do someting
mydict = {'a': 2, 'b': 3}
subfunction(mydict)
print mydict
def otherfunction(thedict):
dict['c'] = 5
If you now run main_function, it will print out a dictionary that includes 'c'.
As misha already said, pickle is a good idea, but an easier way is to use the shelve module,which uses (c)pickle internally and does exactly what you ask for.
From the docs:
import shelve
d = shelve.open(filename) # open
d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of data at key (raise KeyError if no
# such key)
I think it might help to be more specific about the structure of your program. It sounds like you want to persist a dictionary as an external file, to be loaded/reloaded on subsequent runs of your app. In this case you could use the pickle library like so:
import pickle
dictionary = {"foo": "bar", "spam": "egg"}
# save it to a file...
with open("myfile.dct", "wb") as outf:
pickle.dump(dictionary, outf)
# load it in again:
reloaded = {}
with open("myfile.dct", "rb") as inf:
reloaded = pickle.load(inf)

Resources