I can't seem to figure out why there is a parsing error on "else:" in this python code. Please help.
I am trying to count the number of times the same 'email' appeared using dictionary from the text "mbox-short.txt". The final result should print the key (that is the email) and the value (number of times repeated).
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
try:
handle = open(name)
except:
print 'Invalid input.'
quit()
def emailrepeat(s):
d = dict()
if s not in d:
d[s] = 1
else:
try:
d[s] = d[s] + 1
except:
print "error"
return d
for line in handle:
if line.startswith('From:') == True:
continue
if line.startswith('From') == True:
newline = line.split()
email = newline[1]
print email
print emailrepeat(email)
Thanks everyone!
What the **else** mean?
If your want note the else statement, please use the # or '''.
remove the asterisk around else, to make else a comment use #, """, or '''
asterisk will result in error
Related
This program essentially encodes and decodes a message and code respectively. I only did the decoding part so far. However I keep getting an EOF error even though I made sure to end parentheses, checked my syntax and kept tampering with it. Unfortunately no luck. Anyone know why this error keeps popping up? I would greatly appreciate it. Also I copied both files that i'm using.
from LetterCodeLogic import LCL
def main():
print("Welcome to the LetterCode program")
choice = getChoice()
while choice !=0:
if choice == 1:
#Encode logic...
print()
elif choice == 2:
#Decode logic...
msg = input("Enter your numbers to decode (separate with commas): ")
#send msg to Decode function in LCL class (LetterCodeLogic.py file)
result = LCL.Decode(msg)
print("Your decoded message is: \n" + result)
else:
print("Unknown process...")
print()
choice = getChoice()
print("Thanks for using the Letter Code program")
def getChoice():
c = int(input("Choice? (1=Encode, 2=Decode, 0=Quit): "))
return c
if __name__ == "__main__":
main()
class LCL:
"""Encode/Decode Functions"""
#staticmethod
def Decode(msg):
#separate numbers from msg string (e.g., "1,2,3")
nums = msg.split(",") #produces list of separate items
result = ""
for x in nums:
try:
n = int(x.strip()) #remove leading/trailing spaces...
if n == 0:
c = " "
elif n < 0 or n > 26:
c = "?"
else:
#ASCII scheme has A=65, B=66, etc.
c = chr(n+64)
except ValueError:
c = "?"
result += c #same as: result = result + c
return result
#staticmethod
def Encode(msg):
the "#staticmethod" and "def Encode()" function was empty and that was the end of line parsing error. When I was coding this and ran it, it ran with no problems. So I removed it for the time being.
When the Condition matches, It is printing the proper output as expected. But when the condition does not match the "if not found" part is not working.
here If condition checks the username and password both. If it satisfies, It executes the code below it, But when It does not match, It displays blank , I mean there is no Invalid Login printed , though It should get printed
passwd = {}
actual_user = {}
found = False
for row in prsnobj.result:
actual_user[row[0]] = row[1]
for i in range(1, 100):
passwd[row[0]] = row[2]
for i in range(1, 100):
if login == actual_user[i] and password == passwd[i]:
found = True
print "WELCOME !!"
if not found:
print "<h4>Invalid Login</h4>"
You can write this without a flag, using for/else:
for u, p in zip(actual_user.values(), passwd.values()):
if login == u and password == p:
print "WELCOME !!"
break
else:
print "<h4>Invalid Login</h4>"
But it may be better to use a dictionary:
logindb = {row[1]:row[2] for row in prsnobj.result}
if login in logindb and logindb[login] == password:
print "WELCOME !!"
else:
print "<h4>Invalid Login</h4>"
The relevant part of your code could be more simple expressed as this:
if a == 1:
found = True
if not found:
print "not found"
The problem with this is that you never set found to false. Even if a is not equal to 1, found is still true from the last time you found something.
So the solution is something like this:
found = False
if a == 1:
found = True
if not found:
print "not found"
for row in prsnobj.result:
logindb = {row[1]:row[2]}
#print logindb
if login in logindb and logindb[login] == password:
print "Welcome"
break
else:
print "Invalid"
break
I have the following code:
#gets the filename from the user
b= input("Please enter a file name to be opened: ")
a = (b+".txt")
#main data storage and other boolean options
data =[]
result1 =[]
on = True
#File reading in main body with try and except functionality.
try:
check = open(a, 'r')
line =check.readlines()
for items in line:
breakup= items.split()
number, salary, position, first, oname1, oname2, last = breakup
data.append(tuple([last, first + ' ' + oname1 + ' ' + oname2, number, position, salary]))
except IOError as e :
print("Failed to open", fileName)
#Employee creation function, takes the line and stores it in the correct position.
def employee_creation():
result = [((item[0] +", "+ item[1]).ljust(30), int(item[2]), item[3].ljust(15), int(item[4])) for item in data]
for items in result:
result1.append((items[0][0:30], format(items[1], "^5d"), items[2][0:15], "£"+format((items[3]),"<8d")))
return(result)
employee_creation()
print(result)
while on == True:
print("Please select what option you would like to use to search for employees:")
option = int(input("""
1 - Salary (X to X)
2 - Job Titlle
3 - Name, Payroll Number
:"""))
if option == 1:
start = input("What range would you like to start from: ")
end = input("What is the maximum range you would like :")
for items in result:
print(items[3])
if items[3]>start and items[3]<end:
print(items)
else:
print("No employees with this information can be found")
on= False
else:
on= False
However my def employee_creation() doesn't actually return result. I need it to make it a global variable so that I can use it to launch personal querys against the data.
Can anyone see why its not working?
No need to use the evil global variables. You forgot to store the result of your function to another variable.
def employee_creation():
result = [((item[0] +", "+ item[1]).ljust(30), int(item[2]), item[3].ljust(15), int(item[4])) for item in data]
for items in result:
result1.append((items[0][0:30], format(items[1], "^5d"), items[2][0:15], "£"+format((items[3]),"<8d")))
return result # no need for () here
result = employee_creation() # store the return value of your function
print(result)
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
f = open(fileName,'r')
numbers = []
for line in f:
sentenceInLine = line.split('\n')
for word in sentenceInLine:
if word != '':
numbers.append(word)
print numbers
print len(numbers)
print numbers[n-1]
if n == 0:
print "There is no 0 line"
break
i think you missed to split sentenceInLine like sentenceInLine.split(' ')
You are looping over each line, then you split lines based on '\n'. That \n is a line break character. That would confuse your logic right there.
So it is a bit confusing what you are trying to do but you should check n after the user has inputed a value for n. not at the end.
You may want to also catch the exception where file cannot be found I think this is what you need:
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
if n == 0:
print "There is no 0 line"
sys.exit();
try:
f = open(fileName,'r')
except IOError:
print "Could not find file"
sys.exit()
I'm having trouble getting an "Else" statement to work.
My code looks like this so far:
roomNumber = (input("Enter the room number: "))
def find_details(id2find):
rb_text = open('roombookings2.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == (s['Room']):
yield(s)
rb_text.close()
for room in find_details(roomNumber):
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
So when i do a positive search and get multiple matches in my text file, i get well organised results.
However, i'm trying to get it to tell me if invalid input data is entered and re-ask for the room number until the correct data is input.
I tried using an "Else" statement about the "Yield(s)" but it wont accept it.
Any ideas?
Python blocks are delineated by indentation so the "else:" (note lowercase and with a colon to indicate the start of a block) should be at the same indent level as the if statement.
def find_details(id2find):
rb_text = open('roombookings2.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == (s['Room']):
yield(s)
else:
print "this print will execute if d2find != (s['Room'])"
# ... also see DrTyrsa's comment on you question.
But I suspect you don't really want to use an else clause anyway, where would you go from there? This looks an awful lot like an assignment so I'm not going to post an exact solution.
You can do it like this:
def find_details(id2find):
found = False
with open('roombookings2.txt', 'r') as rb_text:
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == s['Room']:
found = True
yield(s)
if not found:
raise ValueError("No such room number!")
while True:
roomNumber = (input("Enter the room number: "))
try:
for room in find_details(roomNumber):
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
break
except ValueError as e:
print str(e)