I know that it is so stupid question but I'm stuck. How should I write this condition:
some_dic = { "single": single_player,
"s": single_player,
...
"m": multiplayer
}
mode_choice = ' '
while mode_choice not in some_dic:
mode_choice = input("Enter The Game Mode: ")
if some_dic(mode_choice) == single_player
...
I mean before the last line, of course. While executing a popup: "'dict' object is not callable" appears. I'm asking for a solution and a some explanation, if it is not a problem.
Best regards
Accessing elements from a dictionary should be done with square brackets:
some_dic[made_choice]
Nevertheless, there's a better pattern you can use to avoid checking the dictionary twice (you are doing it at mode_choice not in some_dic and some_dic[mode_choice] for the same text):
player = None
while player is None:
player = some_dict.get(input("Enter The Game Mode: "))
Like this, player will be either None or one valid output from your dictionary (eg.: single_player) and the loop will persist while it is None.
Related
I have just started learning python and i have been given an assignment to create a list of players and stats using different loops.
I cant work out how to create a function that searches the player list and gives an output of the players name and the players stat.
Here is the assignment:
Create an empty list called players
Use two input() statements inside a for loop to collect the name
and performance of each player (the name will be in the form of a
string and the performance as an integer from 0 – 100.) Add both
pieces of information to the list (so in the first iteration of the
loop players[0] will contain the name of the first player and
players[1] will contain their performance.) You are not required to
validate this data.
Use a while loop to display all the player information in the
following form:
Player : Performance
Use a loop type of your choice to copy the performance values from
the players list and store these items in a new list called results
Write a function that accepts the values “max” or “min” and
returns the maximum or minimum values from the results list
Write a function called find_player() that accepts a player name
and displays their name and performance from the players list, or an
error message if the player is not found.
Here is what I have so far:
print ("Enter 11 Player names and stats")
# Create player list
playerlist = []
# Create results list
results = []
# for loop setting amount of players and collecting input/appending list
for i in range(11):
player = (input("Player name: "))
playerlist.append(player)
stats = int(input("Player stats: "))
playerlist.append(stats)
# While loop printing player list
whileLoop = True
while whileLoop == True:
print (playerlist)
break
# for loop append results list, [start:stop:step]
for i in range(11):
results.append(playerlist[1::2])
break
# max in a custom function
def getMax(results):
results = (playerlist[1::2])
return max(results)
print ("Max Stat",getMax(results))
# custom function to find player
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
return (name)
for s in list:
if name in str(s):
return (s)
print (find_player(playerlist))
I have tried many different ways to create the find player function without success.
I think I am having problems because my list consists of strings and integers eg. ['john', 6, 'bill', 8]
I would like it to display the player that was searched for and the stats ['John', 6]
Any help would be greatly appreciated.
PS:
I know there is no need for all these loops but that is what the assignment seems to be asking for.
Thank you
I cut down on the fat and made a "dummy list", but your find_player function seems to work well, once you remove the first return statement! Once you return something, the function just ends.
All it needs is to also display the performance like so:
# Create player list
playerlist = ["a", 1, "b", 2, "c", 3]
# custom function to find player
def find_player(playerlist):
name = str(input("Search keyword: "))
searchIndex = 0
for s in playerlist:
try:
if name == str(s):
return ("Player: '%s' with performance %d" % (name, playerlist[searchIndex+1]))
except Exception as e:
print(e)
searchIndex += 1
print (find_player(playerlist))
>>Search keyword: a
>>Player: 'a' with performance 1
I also added a try/except in case something goes wrong.
Also: NEVER USE "LIST" AS A VARIABLE NAME!
Besides, you already have an internal name for it, so why assign it another name. You can just use playerlist inside the function.
Your code didn't work because you typed a key and immediately returned it. In order for the code to work, you must use the key to find the value. In this task, it is in the format of '' key1 ', value1,' key2 ', value2, ...]. In the function, index is a variable that stores the position of the key. And it finds the position of key through loop. It then returns list [index + 1] to return the value corresponding to the key.
playerlist = []
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
index = 0
for s in list:
if name == str(s):
return ("This keyword's value: %d" % (list[index+1]))
index+=1
print (find_player(playerlist))
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.
I have a problem with this code. It splits a string into a list and parses through it .I want to do something when I identify a word in the list. I have looked at IF statements and although it makes logical sense the code only produces the statement "screen problem advice" regardless of the sentence inputted. I am a bit stumped as to why i cant use current_word in a conditional statement. Is there something obviously wrong with this?
text=str(input("enter your problem"))
words = text.split()
for current_word in words:
print(current_word)
if current_word=="screen":
print("screen problem advice")
elif current_word=="power":
print("power_problem advice ")
elif current_word=="wifi":
print("connection_problems advice")
Any advice would be much appreciated.
If I run your code on my machine, it works like it should.
Some short pattern for if elif elif elif else is to use some dict() and use the .get()-method for lookups.
Some code like this ...
if word == "one":
variable = "11111"
elif word == "two":
variable = "22222"
elif word == "three":
variable = "33333"
else:
variable = "00000"
... can be written in some much shorter form:
variable = dict(
one="11111",
two="22222",
three="33333"
).get(word, "00000")
Back to your problem. Here is some sample.
I created a detect function which yields all detected advices.
In the main function, the advices are just printed out.
Please note the .lower() inside ISSUES.get(word.lower()), so it catches all variation of "wifi", "Wifi", "WiFi", ...
def detect(message):
ISSUES = dict(
wifi="network problem_advice",
power="power problem_advice",
screen="screen problem_advice"
)
for word in message.split():
issue = ISSUES.get(word.lower())
if issue:
yield issue
def main(message):
[print(issue) for issue in detect(message)]
if __name__ == '__main__':
main("The screen is very big!")
main("My power supply is working fine, thanks!")
main("Wifi reception is very good today!")
Further, I deliberately chose some weird examples to point you to some basic problem with your attempt to solve the problem.
A simple string matching won't be enough, as is produces false-positives in this case.
Try to think of some other approach.
Here is my code:
def collectData():
print ("Please use correct spelling\n")
print("Choose what game type this is")
getGameType = input(" FFA: 1\n 1v1: 2\n 2v2: 3\n 3v3: 4\n 4v4: 5\n")
if getGameType == "1":
FFAPlayerList = []
getFFAMaxLen = (int)(input("How Many players were in this FFA?: "))
print("Please enter playername as well as placing, seperated by a comma\n(playerName,placing) One player per entry. \n")
while len(FFAPlayerList) < getFFAMaxLen:
getFFAPlayers = input("format: playerName,Placing::: ").split(',')
FFAPlayerList.append(getFFAPlayers)
with open("C:\\Users\\Twinklenugget\\Documents\\NQGroup\\Databases\\NQMasterDatabase.csv", 'r') as ffaDatabaseExtract:
reader = csv.reader(ffaDatabaseExtract)
ffaDatabaseList = list(reader)
FFAPlayerList.append(ffaDatabaseList)
print (FFAPlayerList)
collectData()
Forgive the formatting, it's actually all correct. I am relativly new to python and coding in general. My goal is to be able to take the values stored in FFAPlayerList (the player names) and use those strings to look for the same strings in ffaDatabaseList. After it finds the same strings from ffaDatabaseList I then need to take values from the second column from ffaDatabaseList and append them into FFAPlayerList. How exactly would I go about doing that? Even a pointer in the right direction would be great.
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)