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!).
Related
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.
# 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.
I am trying to implement a solution where I call the displayPerson() that takes the user input for an id number and will print the information for the user. I should note that I'm downloading a csv file from the internet that contains data in this format:
id, name , birthday
1, Jack Sparrow, 09/20/2000
My goal is to get a number from the user which will look up and display the ID. I want the prompt to continue to show up and ask the user for a number until they enter a negative number or 0 to exit.
page = downloadData(args.url)
persons = processData(page)
prompt= int(raw_input(" Enter ID of person you would like to search for: "))
displayPerson(prompt, persons)
displayPerson(prompt, persons)
When I try to pass the raw input of a number 1-99 I get a Key Error, even though there are ids with that number. If I simply hard code displayPerson(10, persons) for example, the code will run but if I raw_input 10 I will get an error. Why?
Here is my displayPerson function:
def displayPerson(id, personDataDictionary):
"""
:param id:
:param personDataDictionary: Look at displayPerson in __name__ function. But I thought bday was pieces[2].
:return:
"""
print("id = {}, name = {}, birthday = {}".format(id, personDataDictionary[id][0],
personDataDictionary[id][1].strftime("%Y-%m-%d")))
As it is written I can call the function using the former code snippet (the first one you see up there) and the program will run fine if I enter an integer as one of the parameters manually but won't allow me to take a value from 1-99 without throwing a Key Error. How do I accomplish this?
Where is the dictionary that you are raising the Key Error on? Are the keys inputted as integers or strings? That could be one element you want to look into. I'm not 100% sure what you're asking for but if it's how to restrict the value of the var prompt to be between 1 and 99:
prompt = 0
while prompt < 1 or prompt > 99:
prompt = int(raw_input(" Enter ID (1 - 99) of person you would like to search for: "))
do_something_with_key(prompt)
By the time you exit this loop, the value of prompt will be what you are looking for (unless what you're looking for is a string).
On my view,i suggest you to do this.
Reason:why you throw a Key error because your dictionary did not have such key,so you should care about if you can get the value by key instead of setting range
def displayPerson(id, personDataDictionary):
"""
:param id:
:param personDataDictionary: Look at displayPerson in __name__ function. But I thought bday was pieces[2].
:return:
"""
per = personDataDictionary.get(id)
while not per:
prompt = int(raw_input(" Enter ID of person you would like to search for: "))
per = personDataDictionary.get(prompt)
print("id = {}, name = {}, birthday = {}".format(id, per[id][0],
per[id][1].strftime("%Y-%m-%d")))
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]]))
For School I am meant to create a program that identifies your mood and then tells you what it really is. Anyway with my code I keep getting errors about the way I have assigned values to my strings. Currently my code looks like this:
import random
smiles = ['XD',';)',':)',':()',':(']
history = []
reality = random.choice(smiles)
('XD')= 5
(':)') = 4
(':|') = 3
(':T') = 2
(':(') = 1
def menu():
print (smiles)
int(input("Which emoticon do you relate to?"))
if 1:
print("You are Fealing like XD")
print("but in reality you are feeling like", reality)
etc
Thanks.
As said in the comments, you cannot assign a value to a string, you need to store them in a type of a collection, dictionary or list etc.
Given that you're asking for a number from the user, you can just assign the users input to a variable then compare that against the index in the array. Feel free to add error handling here for an input that is outside the length of the array.
int(input("Which emoticon do you relate to?"))
if 1:
could be
user_input = int(input("Which emoticon do you relate to?"))
if user_input - 1 == 0: # -1 since lists are 0 indexed.
You could make this generic as well and remove the if statement and just use
users_smile = smiles[user_input - 1]
print("You are Fealing like {}".format(users_smile))
You can't assign value to string as #juanpa.arrivillaga said so you should use dictionary
smiles_dict = { 5: 'XD', 4: ':)', 3: ':|', 2: ':T', 1: ':(' }
and then use
smiles_dict.get(reality)
hope this might help you