Simple length validation to a key in a dictionary in python? - python

I'm currently making a validation system to check the length of the key in my dictionary and remove any added value when it goes over a specific length but the thing is when I try to making it doesn't seem to work and . Here's what I've done
team1 = {"Team Ahab":["Martin","Kaz","Simba","Davis","Yas",],"Score":[]}
username = input("What is your name:")
if len(team1["Team Ahab"]) > 5:
team1["Team Ahab"].pop(username)
print("This team is full so please join another one instead")
else:
team1["Team Ahab"].append(username)
print(team1)
Here's my ideal output
username = "Paul"
This team is full so please join another one instead

Your validation logic validates the team after adding the wrong member and then corrects this error. Using this logic, you should always append the new member to the team before performing any validations:
team1["Team Ahab"].append(username)
if len(team1["Team Ahab"]) > 5:
team1["Team Ahab"].pop(username)
print("This team is full so please join another one instead")
else:
print(team1)
Alternatively, you could check if the team's size is exactly five before appending to it. Note that in this case yu should not pop the last member of the team:
if len(team1["Team Ahab"]) == 5:
print("This team is full so please join another one instead")
else:
team1["Team Ahab"].append(username)
print(team1)

I've modified code as below:
team1 = {"Team Ahab":["Martin","Kaz","Simba","Davis","Yas",],"Score":[]}
username = input("What is your name:")
if len(team1["Team Ahab"]) >= 5 :
if(username in team1["Team Ahab"]):
team1["Team Ahab"].remove(username)
print("This team is full so please join another one instead")
else:
team1["Team Ahab"].append(username)
print(team1)
Changes:
Condition needs to be len(team1["Team Ahab"]) >= 5 and (username in team1["Team Ahab"])
list.pop(index) expects a index, not str. Here, you can use remove function.

Related

How to fix IF/ELSE statments?

I'm trying to create an authorization process and it always says name unauthorized, despite the name not being assigned to the unauthorized variable.
I've tried different organization of the code, ie different order, but the problem hasn't improved.
Tessa=str
un = Tessa
n1=str
n2=str
input(n1("What is the name of player one?"))
if n1 == un:
print("Name unauthorised, try again")
else:
print ("Name authorised")
input(n2("What is the name of player two?"))
if n2 == un:
print("Name unauthorised, try again")
else:
print("Name authorised")
print("Welcome")
I expect any inputted name other than Tessa to result in the phrase "Name authorized" but instead it prints the unauthorized message."
I don't understand the statements n1 = str. Please check my code.
un = 'Tessa'
n1 = input("What is the name of player one?")
if n1 == un:
print("Name unauthorised, try again")
else:
print ("Name authorised")
n2 = input("What is the name of player two?")
if n2 == un:
print("Name unauthorised, try again")
else:
print("Name authorised")
print("Welcome")
and the result will be as below.
What is the name of player one? lam
Name authorised
What is the name of player two? rio
Name authorised
Welcome
you're clearly new to Python, so here are some things that you should fix:
Python doesn't need variables to have certain type. There is no need for what you were intending with n1 = str.
If you want to assign an actual string value, you can do so using quotes: "my string value".
If you want to do repeated checks, do it as part of a loop
If you want to store multiple values, use a list. (like for player names)
If you might have multiple values to check against (you might have multiple unauthorised names), use a list.
In light of these, consider the following code snippet:
unauthorised_names = ["Tessa"]
player_names = []
while len(player_names) < 2:
name = input("Please enter a name for player {}:".format(len(player_names) + 1))
if name in unauthorised_names:
print("Unauthorised name, please try again")
else:
player_names.append(name)
print(player_names)
Here unauthorised_names holds every name that cannot be entered. It can be one, it can be many.
player_names contain the names of the players.
You run it, until you got a sufficient number of valid player names, with the while loop
You take the input, with the number of the player as a parameter
Check it if it's on the list of invalid names, and store it, if it isn't.
Once you have the right number of names, you proceed with your program.
Try it for yourself!
To take an input and keep the value in n1, you need to do this:
n1 = str(input("What is the name of player one?"))
Also, I have no idea where you're going with the n1 = str, etc., so I suggest you scrap it.

How to include 1st, 2nd, 3rd instead of writing it out

# extension
modify = input("Would you like to modify your recordings? Yes or No? ")
if modify == ("Yes","yes","Y","y"):
print ("OK")
if modify == ("No","no","n","N"):
print ("You may now exit the program")
print("")
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
if name == ("Jane, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Grant, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Lilly, Under 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Henry, Over 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Jane, Over 11"):
answer = input ("Would you like to add or delete data? ")
if name == ("Naomi, Over 11"):
answer = input ("Would you like to add or delete data? ")
if answer == ("add" ,"Add"):
pos = input ("Type in the position(s) you would like to add: ")
elif answer == ("delete" ,"Delete", "del", "Del"):
delete = input ("Would you like to delete position or name?")
if delete == ("pos","Pos","Position","position"):
print ("Position deleted. Here is the final outcome: ",name)
elif delete == ("Name", "name"):
print ("Name deleted. There is no data now")
if pos == ('1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th','11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'):
print ("Posititon added. Here is their final score: ", name, " ", pos)
Hello. I am new to SO so I'm not sure if this is the correct way to do this however I am trying to answer a question where I am told to use pickle and store data inside a file. I am also told that the code should be able to let the user select a list to delete, be able to change a player position(its about a tennis competition) and be able to store the position of players in their last three tournaments. I need to do it in certain age categories
Everything works well so far however I need to do the positions as 1st 2nd 3rd and so on up to 1000. I have started writing it out(see penultimate line) but it would take extremely long to write it out so does anyone know a way to save time and solve this problem??
This is an odd little program, which will break if you don't enter answers with exactly what you're expected to enter.
I was able to get your error when I typed "No" (accidentally) after the prompt "Whose score would you like to modify?"
Since you haven't instantiated the variable answer before your if statements (as #Enes pointed out) and since none of your if statements are true, I didn't have anything stored in the answer variable, when you called
if answer == ("add" ,"Add"):...
this threw an error.
So if you fix the error that #Schlator mentioned
(Change
if modify == ("Yes","yes","Y","y"):
to
if modify in ("Yes","yes","Y","y"):
everywhere)
and if you instantiate your variable answer as Enes mentioned
(Add
answer = ""
before
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
)
then at least your fragile little program will exit gracefully.
It appears that you are mistaken with the syntax
It shouldn't be
if modify == ("Yes","yes","Y","y"):
rather it should be
if modify in ("Yes","yes","Y","y"):
Similarly for other if conditions that you have used in other parts of the program.
The way you've written your program, you will always drop through to if answer == with answer being undefined. Your input and test sequence:
name = input ("Whose score would you like to modify? Type it in with this format - Name, Age Category: ")
if name == ("Jane, Under 11"):
cannot possibly match the choices you've given, because every input will contain a newline. You need to either include that in your test, or strip it from the input before checking.

Resolving "no column name: " for string inputs in sqlite and python?

Essentially, I am asking (1) What column the user wants to edit (UPDATE) and (2) What new value they want to update said column which. This is specified with WHERE id = x.
My problem is that, when updating the value for that column (say, updating "english" with "maths" for the "subject" column), it brings up the error:
sqlite3.OperationalError: no such column: maths
At the moment, I print out a list of options for the user, from which they select what column they want to update. Note that, before this, they have specified what ID they want to edit, so no worries here. I've tried creating parameters and all, but my program will still fall back to "no column name: ". I suspect this is because sqlite cannot handle variables from Python, but I'm still stuck here.
print("[Which information would you like to edit?]")
edit_options = {1: "subject", 2: "education", 3: "years", 4: "nostu", 5: "fptime"}
edit_values = {1: get_one.subject, 2: get_one.education, 3:get_one.years, 4:get_one.nostu, 5:get_one.fptime}
while True:
try:
edit_number = int(input("\n>>> "))
if edit_number < 1:
print("Please enter a number between 1 and 5")
elif edit_number > 5:
print("Please enter a number between 1 and 5")
else:
break
except:
print("Please enter a number between 1 and 5")
edit_column = edit_options[edit_number]
edit_column_value = edit_values[edit_number]
print('''
Editing {0}
[Current Value]: {1} = {2}'''.format(get_one, edit_column,
edit_column_value)) #get_one() is simply an instance from another class
edit_input = input("[New Value]: {0} = ".format(edit_column))
cur.execute("UPDATE teachers SET {0} = {1} WHERE id = {2}".format(edit_column, edit_input, index))
smdb.commit()
print("edit succesful")
Essentially, I want the user's input to update a certain column, where the previously entered ID is entered. Any help is greatly appreciated. I've noted that when entering INT values, this works - it just doesn't work with strings.
(Sorry if my code isn't highlighted, I don't know how!).

How to choose the word in the dictionary menu?

I am writing a English dictionary using python 2. I created a dictionary. for example, "home" and "horse" in the dictionary's key. If the user types "ho", "home" and "horse" will come. I put these in the bottom line. But when the user selects word 1, I want to call the key and value in the dictionary that I set first. How can I do it?
myEngDict = {"horse": "The horse (Equus ferus caballus) is one of two extant subspecies of Equus ferus","home": "the place where one lives permanently, especially as a member of a family or household."}
def Words():
word_List = []
count = 0
search_words = raw_input("Please enter a search term: ")
for i in myEngDict.keys():
if i.startswith(search_words):
count+=1
word_List.append(i)
print "{}{}{}".format(count,".", i)
else:
pass
choose = input("Which one?")
For example, if "home" comes out first, user choose 1:
Program display:
home: the place where one lives permanently, especially as a member of a family or household.
First, you should use raw_input in that final line. Then you need to look up the provided in the word_List.
while True:
try:
choose = int(raw_input("Which one?"))
# Keep the key as a separate variable for faster reference
key = word_List[choose - 1]
# Use labels with the format function. It's easier to read and understand
print '{label}: {text}'.format(label=key, text=myEngDict[key])
# Be sure to have a break or return on success.
return
except ValueError:
# If someone provides 'cat', it will raise an error.
# Inform the user and go back to the start.
print 'Please provide an integer'
except IndexError:
# The user has provided a value above the length of word_List or
# less than one. Again, inform the user and go back to start.
print 'You must enter a number between 1 and {c}'.format(c=len(word_List))
By not changing to much your code, you can just add a print statement after choose in your function at the same identation:
print ("%s : %s"%(word_List[choose-1], myEngDict[word_List[choose-1]]))

Dictionaries: How to get duplicate input by the user and count how many times it was entered?

names = []
print("Duplicate names won't be in the list!") # reminder
while True:
userInput = input("Enter a name: ")
if userInput == "": # condition to terminate loop
print("You've entered these names, duplicated names won't be included")
print(names)
break
elif userInput not in names: # condition to see if input is duplicated
names.append(userInput) # if satisfied, adds it to the list
else:
print("value exists!") # reminder about the value entered is duplicate
That's my code so far, I don't know how could I count how many times a specific duplicate value was entered, a Dictionary will solve it a lot of people say but I am not too familiar yet with it. In the output, When the input of names is complete, the console user should be able to search the list for
names by simply typing the name at the console. The program should output either “Not
found” or display the name and the number of times it was entered.
When the searching is complete, the console user should be able to delete names from the list
by typing the name. If a name is not found, the program should output “Not found”. If a name
is found then it should be removed from the list and the name is displayed along with a
“Deleted” message to the user e.g. “Deleted Ted”.
Thank you very much to people that would help!
You should use a Counter.
c = Counter() #Initialize the counter
print("Duplicate names won't be in the list!")
while True:
userInput = input("Enter a name: ") #input used to be raw_input in Python 2
if userInput == "":
print("You've entered these names, duplicated names won't be included")
print(c.keys())
break
elif userInput not in c:
c.update([userInput]) # if satisfied, adds it to the counter. You have to provide a list, hence the [ ]. If you provide a string, it will be broke down into characters.
else:
print("value exists!")
In order to show a specific count,
print c[word]
You can also see the most common terms, etc.
However your code forbids that a name be entered more than once, but if you want to count the number of times people enter your name, this is the way to go.
A dictionary consists of a key and a value, a key in a dictionary should always be unique, so unless you have a unique key with every value you use, it wouldn't support duplicate values and will not suit your purposes.

Categories