Reputation: 79
I'm creating a menu in python and cant seem to get it working on the one section.
my code searches the postcode column from the user raw_input
.
I want the code to just simply go back to the menu if the raw_input
does not match a postcode in the customer.csv
Customer.csv
1,Lee,test1,dy4zzz,121111111,3,4
2,luke,test2,dy5xxx,854539116,5,6
3,alex,test3,dy1ttt,7894561230,9,8
4,aaron,test4,b65yyy,16464634676974,8,9
code from program
import csv,os,time,math
def menu():
print (""" Main Menu
1.Add New Route
2.Add Customer
3.Edit Customer
4.View Customer
5.Exit """)
ch=raw_input("Enter your choice")
if ch=="1":
NewRoute("Route.csv")
elif ch=="2":
cid=readfile("customer.csv")
addtofile("customer.csv", cid)
menu()
elif ch=="3":
editrecord("customer.csv")
os.remove("customer.csv")
os.rename("temp.csv","customer.csv")
menu()
elif ch=="4":
readfile("customer.csv")
menu()
elif ch=="5":
exit()
elif ch !="":
print ("try again")
menu()
def NewRoute(file_name):
print "Route Calculator"
f=open("route.csv","w")#Opens Route file for writing
f.truncate() #clears all contents from file so a new route can be written to it
f.close() #saves and closes route file
driver=raw_input("Enter Drivers Name: ")
readfile("customer.csv")
cur = (0, 0)
route = [0]
xy = [ ]
z= ()
zz= []
n = input("Please input the amount of destinations you want to visit:")
a = range(1, n + 1)
cidd = []
record = [1]
for i in range(n):
cid=raw_input("Enter Postcode with no spaces and in lowercase:")
f3=csv.reader(open("customer.csv",'r'))
for row in f3:
if row[3]==cid:
x=eval(row[5])
y=eval(row[6])
z=row[1]
xy.append((x,y))
zz.append(((cid,z)))
cidd.append((cid,z))
Upvotes: 0
Views: 95
Reputation: 2344
If what you really want is to exit if a matching postcode
is not found, this ought to help. First, finding a matching postcode is a nice bit of code that may be extracted and placed in it's own function like below. I'm not sure if postcode is the 3rd record or not, update the REC_ constants as necessary.
# Constants for accessing your CSV record (up to postcode)
REC_NUM = 0
REC_NAME = 1
REC_FIELD3 = 2
REC_POSTCODE = 3
def matching_postcode_row(post_code):
reader = csv.reader(open('customer.csv'))
for rec in reader:
if post_code == rec[REC_POSTCODE]:
return rec
return None
With the matching_postcode_row function written, you can now call it like so:
cid=raw_input("Enter Postcode with no spaces and in lowercase:")
rec = matching_postcode_row(cid)
if not rec:
return
As a matter of style, you should rename NewRoute to new_route. CamelCased names are generally used for classes only.
Upvotes: 1