[Tutor] searching data from a list read from a file
Peter Otten
__peter__ at web.de
Sun May 15 13:32:06 CEST 2011
Lea Parker wrote:
[Lea, please reduce the number of empty lines in your posted source code.]
> When you have time I would like some advice on where to go. I have created
> a program that reads charge account numbers from a file. The user is to
> enter a charge account number from the list presented and the program
> should then tell them whether they have entered a valid or invalid number.
> My problem at this stage (and yes there a probably more than this one), is
> when I run the program it tells me the charge account number is always
> invalid even when I put a correct number in. Below is my code because I am
> thinking that perhaps it is an indent issue maybe.
Hint:
What is the type of the values in the account_number list?
What is the type of the value stored in the search variable?
What's the result of a comparison like
42 == "42"
in Python?
> """This program reads the contents of a file into a list. Asks the user
>
> to enter a charge account number and will determine the validity of the
>
> number entered to return a message of either valid or invalid.
>
>
>
> Written by: Leonie Parker 11428070
>
> Subject: ITC Principles of programming
>
> Assignment: 2b"""
>
>
>
> def main():
>
> try:
>
> # Open file for reading
>
> infile = open('charge_accounts.txt', 'r')
>
>
>
> # Read the contents of the file inot a lsit
>
> account_number = infile.readlines()
>
>
>
> #Convert each element into an int
>
> index = 0
>
> while index != len(account_number):
>
> account_number[index] = int(account_number[index])
>
> index += 1
>
>
>
> # Print the contents of the list
>
> print account_number
>
>
>
> #Get an account number to search for
>
> search = raw_input('Enter a charge account number: ')
>
>
>
> #Determine whether the product number is in thelist
>
> if search in account_number:
>
> print search, 'charge account number is VALID'
>
> else:
>
> print search, 'charge account number is INVALID'
>
>
>
> infile.close()
>
>
>
> except ValueError:
>
> print 'file open error message'
>
>
>
> #Call the main function
>
> main()
>
>
>
>
>
>
>
> Thanks in advance
More information about the Tutor
mailing list