Syntax error that I can't figure out - python

Yes I realize I made a mistake about editing original question out, so here it is again; note that I instantly asked another question because I previously had this area in another project I practiced on that I gave up on with the same issue and I couldn't figure out how to fix it.
def overwrite():
print "Which save file would you like to overwrite?"
print "Save file 1 contains:" x['name']
print "Save file 2 contains:" y['name']
print "Save file 3 contains:" z['name']
ovw=raw_input()
if ovw.lower() == 1:
write_data({'name':name, 'fname':'ply.json'}, 'ply.json')
elif ovw.lower() == 2:
write_data({'name':name, 'fname':'ply1.json}, 'ply1.json')
elif ovw.lower() == 3:
write_data({'name':name, 'fname':'ply2.json}, 'ply2.json')
else:
print "I don't understand that. Let's try again."
overwrite()
"x" is causing a syntax error on line three and I don't know why.

Well, first of all, the body of the function overwrite() should be indented; but I'm assuming that is a copy-and-paste fault. To fix your specific issue, you need a comma between the arguments for print. It should be:
print "Save file 1 contains:", x['name'] # notice the comma before the x
The same goes for the other print statements.
Also, you have some missing apostrophes/quotes. Where you have 'fname:'ply1.json', it should be 'fname':'ply1.json' (this occurs in two places).
Edit:
If you keep getting "unexpected indent" errors, then it is likely that you are mixing tabs and spaces in the file. (I get this all the time when I switch editors...)

The print statement with x['name'], y['name'] and z['name'] are not concatenated properly to the first part of the string. You should show us the actual errors you're receiving. If x['name'] is a string, the line could be properly written as:
print "Save file 1 contains:" + x['name'] # plus sign
or
print "Save file 1 contains:", x['name'] # comma
And the same for the print statements for y and z
def overwrite():
print "Which save file would you like to overwrite?"
print "Save file 1 contains:" x['name'] # x['name'] part is not concatenated properly to the first part of the string
print "Save file 2 contains:" y['name']
print "Save file 3 contains:" z['name']
ovw=raw_input()
if ovw.lower() == 1:
write_data({'name':name, 'fname':'ply.json'}, 'ply.json')
elif ovw.lower() == 2:
write_data({'name':name, 'fname':'ply1.json'}, 'ply1.json')
elif ovw.lower() == 3:
write_data({'name':name, 'fname':'ply2.json'}, 'ply2.json')
else:
print "I don't understand that. Let's try again."
overwrite()

Related

Python switching the display based on input using If, Else

I want to display print text based on my Input value using IF/Else or Switch. And Also let me know how to use switch case for below code.
# OnButtonOK after clicking it, display the input value
def OnButtonOK(self):
Input = self.entrytext.get()
# self.text.insert(END, Input + '\n')
# self.scroll.config(Input = self.text.yview)
print Input
useroption = atoi(Input)
# self.OnButtonClick();
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
return;
def SubMenu1(self):
print 'SubMenu1'
return;
def SubMenu2(self):
print 'SubMenu2'
return;
def SubMenu3(self):
print 'SubMenu3'
return;
I am able to print only else part:
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
Let me know where exactly i am going wrong.
I think you have indentation problems in your code:
Python use 4 spaces(you can use 1 space but 4 is good practice) indentation language. Means if/else statement will be like this:
if a == 1:
print("A = 1") # 4 spaces w.r.t to above statement
elif a == 2:
print("A = 2")
elif a ==3:
print("A = 4")
else:
print("A = pta nahi")
you can use above if/else statements as a switch case and also your indentation problem will be solved
It's a simple beginner's mistake, you're indenting it worng:
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
should be
if (useroption == 1):
print "input is output" # You had an indent too many here
self.SubMenu1();
else:
print "Error:Invalid"
Python is indentation sensitive; too many or too few indentations will break your code.

SyntaxError at Cloud9 IDE? Is this a bug or did I do something wrong?

I believe I have found a bug with the Cloud9 IDE, as I get a syntax error in the following code:
for x in optionMenu:
print x[0], x[1]
action = raw_input ("Please select an action: ")
if action == "1":
direction = directionMenu()
if direction == "East":
validAction = True
print "You raise the portcullis and enter the palace."
room2(character)
else:
print "You can't go that way!"
elif action == "2":
characterMenu(character)
elif action == "3":
if searched_yet1 == False:
skill_pass = skillCheck(1, character.search)
if skill_pass == True:
print "The double portcullis seems moveable with some effort."
searched_yet1 = True
else:
print "You fail to find anything worthy of note. "
searched_yet1 = True
else:
print "You have already attempted that action!"
elif action == "4":
if listened_yet1 == False:
skill_pass = skillCheck(5, character.listen)
if skill_pass == True:
print "Sounds coming from deep in the palace can be heard every few minutes."
listened_yet1 = True
else:
print "You fail to hear anything worth of note. "
listened_yet1 = True
else:
print "You have already attempted that action!"
The syntax error occurs at "elif action == "4":. AmI doing something wrong or have I found a bug with the Cloud9 IDE? I have tried adjusting the spacing. Is there an error with the above print statement?
EDIT: Version is Python 2.7.6, error is
File "/home/ubuntu/workspace/dungeonMap.py", line 63
elif action == "4":
^
SyntaxError: invalid syntax
As I examine your code as posted here, the line elif action == 4: is preceded by 4 spaces then 2 tabs. Mixing spaces and tabs in Python is a very bad idea. I also see that some lines, such as the preceding one, use only spaces for indentation.
Replace those two tabs, as well as any others, with spaces, and configure your IDE to use only spaces when indenting. See if that solves the problem.
After looking more closely, I now see the direct problem. I believe that Python treats a tab as 8 spaces, no matter how it appears in your editor. Given that, your line two lines above your problem line is an else: but is indented to conclude the if action == "1": line rather than the if searched_yet1 == False: line that you intended. Python then sees your elif action == 4: line as an elif without a corresponding prior if.
Again, replacing all those tabs with spaces and then getting the indentation to look right will solve that problem and others.

Not able to understand where white spaces are or indentation is missing in Python code : Line 6: SyntaxError: bad input (' ')

def name_to_number(name):
if name=='rock'
number=0
elif name=='Spock'
number=1
elif name=='paper'
number=2
elif name=='lizard'
number=3
elif name=='scissors'
number=4
else
print'Not a valid input'
return number
You are missing the colon at the end of each if and elif statement.
This is invalid:
if name == 'rock'
number = 0
Python uses the colon as an indication that the next line should be an indented block. If you miss this colon then python thinks the next line should not be indented.
This is valid:
if name == 'rock':
number = 0
As a general debugging principle if you get an error message and you cannot see anything wrong with the line number the error mentions check the previous line. An error in the previous line might not be discovered by the python interpreter until it reaches the next line and cannot interpret it.
Try this:
def name_to_number(name):
if name=='rock':
number=0
elif name=='Spock':
number=1
elif name=='paper':
number=2
elif name=='lizard':
number=3
elif name=='scissors':
number=4
else:
print 'Not a valid input'
return number
With Python, indentation plays an important role. Read up here: https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Indentation

How do i get python to remove the row i search for from csv file

I am able to edit and add new entries but everytime i try to delete the row i search for, it wipes the whole files data.
I need it to just remove that row of data without losing the rest of the rows.
import csv,os,sys
def helper(file):
o=csv.reader(open(file,"r"))
for row in o:
print row
def delete(filename):
found=False
f1=csv.reader(open(filename,'r'))
f2=csv.writer(open("temp.csv",'a'))
rid=raw_input("Enter name to find record:")
for row in f1:
if rid in row[0]:
found=True
f2.writerow()
print rid, "has been deleted from the database!"
else:
found=False
if found==False:
print "That name isn't in our database!"
z=raw_input("Please enter 1 to retry, 2 to return to log in, or 3 to close program:")
if z=="1":
delete(filename)
if z=="2":
import program
if z=="3":
exit
helping=raw_input("Do you require any help with using this feature?Type y for yes or just hit enter to continue:")
if helping=="y":
helper('deletehelp.txt')
delete("custdet.csv")
os.remove("custdet.csv")
os.rename("temp.csv","custdet.csv") #This is the file rename that I mentioned above.
restart=raw_input("Would you like to return to the main menu? Please type Y or just hit enter to exit:")
if restart=="y":
import program
else: exit
import csv,os,sys
def helper(file):
o = csv.reader(open(file,"r"))
for row in o:
print row
def delete(filename):
f1 = csv.reader(open(filename,'r'))
f2 = csv.writer(open("temp.csv",'a'))
rid = raw_input("Enter name to find record:")
found = False
for row in f1:
if rid not in row[0]:
f2.writerow(row)
else:
found = True
print rid, "has been deleted from the database!"
if found == False:
print "That name isn't in our database!"
z = raw_input("Please enter 1 to retry, 2 to return to log in, or 3 to close program:")
if z == "1":
delete(filename)
if z == "2":
import program
if z == "3":
exit
You never actually write to the new csv file.
Look at the main filter/copy loop:
# for every row in the input file
for row in f1:
# Is this the/a record to delete?
if rid in row[0]:
# yes!
found=True
# then we do not write anything to the output file (???)
f2.writerow()
print rid, "has been deleted from the database!"
# no else part, so no nothing gets done with
# the input row `row` ...
So you'll end up with an empty output file ...
Change the section containing the for loop to this:
for row in f1:
if rid in row[0]:
found=True
print rid, "has been deleted from the database!"
else:
f2.writerow(row)
The changes:
Actually write the row if rid is not in row[0]
Don't reset the found flag to False
The rest of the code also needs some work:
Recursion is not the best way to handle retries, use a loop instead.
import program to return to the login ????? That's not going to
work. Perhaps you should just return from the function.
There is coupling between delete() and the calling code which
relies on a file named temp.csv being created. It would be much
better if delete() performed the renaming of the temporary file itself.

Saving/Loading lists in Python

I am new to python (and programming in general) and am making a database/register for a typical class. I wanted the user to be able to add and remove pupils from the database, I used lists primarily for this but have hit a stump.
Whenever I restart the program the list the user has modified returns back to the defualt list I specified in the code. I looked around the internet and tried to save the list onto a seperate txt file. However the txt file also goes back to the defualt every time I restart the program. I would like you to please give me a way to save the changes made to the list and keep them that way. Here is the code (it's not very good):
def menu():
print "*****************CLASS REGISTER*****************"
print "Press 1 See The List Of Pupils"
print "Press 2 To Add New Pupils"
print "Press 3 To Remove Pupils"
print "Press 0 To Quit \n"
filename = open('pupil.txt','r')
pupil = ["James Steele", "Blain Krontick", "Leeroy Jenkins", "Tanvir Choudrey"]
def see_list(x):
print x
def add_pupil(x):
print "You have chosen to add a new pupil.\n"
option = raw_input("Please type the childs name.")
x.append(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been added to the system."
return x
def delete_pupil(x):
print "You have chosen to remove a pupil.\n"
option = raw_input("Please type the childs name.")
if option in x:
x.remove(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been removed from the system."
else:
print "That person is not in the system."
return x
one = 1
while one != 0:
menu()
option = input()
if option == 1:
see_list(pupil)
elif option == 2:
add_pupil(pupil)
elif option == 3:
delete_pupil(pupil)
elif option == 0:
break
else:
print "That is not a valible choice."
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
if option == 0:
quit
Well, you just open the pupil.txt file but never read back its contents. You need something like this:
filename = open('pupil.txt', 'r')
contents = filename.read()
filename.close()
pupil = [name for name in contents.split('\n') if name]
Also, you will need to handle the case when the pupil.txt file does not exist; this can be done with a try..except block around the IO calls.
Finally, as one of the comments has mentioned above, have a look at the pickle module, which lets you store a Python object in a file in Python's internal format (which is not really readable, but saves you a lot of hassle).
Not related to your question directly, but this:
one = 1
while one != 0:
...
is silly. All you need is:
while True:
...
This is what a database is for. Use sqlite - a simple file-based database the libraries for which come bundled with python.

Categories

Resources