I was tasked with the following
1. Design and write a program to simulate a bank. Your program should read account numbers, PINs,
and beginning balances from a text file. Each line of text in the input file will have all the information
about a single bank account - account number, PIN and beginning balance. All information fields are
separated by semi-colons. Here is some sample input:
516;5555;20000
148;2222;10000
179;9898;4500
My problem is I don't know how to turn these elements into integers I can manipulate such as were someone to withdraw money, here is what I have so far
def bank():
myfile = pickAFile()
file = open(myfile)
contents = file.readlines()
for i in range (0, len(contents)):
items = contents[i].split(";")
choice = requestInteger(" 1 - Withdraw, 2 - Deposit, 3 - Exit program ")
if (choice == 1):
PIN = requestInteger("Please enter your PIN")
if (PIN == items[1]):
print items[0]
print("Invalid PIN")
My if statements wont work though because everything in items is a string not an int, the language is JES which uses python syntax but java libraries
--- NEW ANSWER ---
Thanks for the feedback - you can use the same casting technique with a list comprehension.
items = [int(j) for j in contents[i].split(";")]
You could optionally surround it with a try/except block too, depending on how confident you are of the incoming data quality.
--- OLD ANSWER ---
You can cast it as an integer right after the requestInteger() call:
...
choice = requestInteger(...)
try:
choice = int(choice)
except ValueError:
# Spit some error message back
if (choice == 1):
...
Related
My question is about getting a user to pull and item from a list. If the item from the list isn't pulled from the list I want to tell the user that he is incorrect. So my code looks like this:
Body_Type = ['Large', 'Medium', 'Small']
print('Create a Character-')
print('Body Type Choices: ' + str(Body_Type))
bt = input('Enter your Body Type: ')
while bt != Body_Type:
if bt == Body_Type[0:]:
print('Your Body Type is: ' + bt)
else:
print('Invalid Body Type')
What I'm trying to do is make my user create a character. This is just the first part of my first simple project. I want to have him pull from one of the items on the list, being "Large, Medium, Small" respectively. I want it to repeat until the user chooses one of the three. I tried to use or but it seems to feel unorganized and I'd have to break up the list and assign each individual variable.
Thanks in advance!
Several errors here like comparing a string to a list, or random slicing hoping that it would work. And the fact that your input statement is before the loop creates an infinite loop because you're comparing 2 variables of a different type again and again (bt != Body_Type is always True regardless of the content of bt since left hand is a string, right hand is a list).
But it shouldn't be so complex to write some working code.
I would create an infinite loop and break only if choice is in the list:
while True:
bt = input('Enter your Body Type: ')
if bt in Body_Type:
print('Your Body Type is: ' + bt)
break
else:
print('Invalid Body Type')
simpler and clearer (and repeats input if fails). The infinite loop (with an always true condition) allows to avoid double input call & test. Just loop, input the string, and break from the loop if matches.
The key statement you were looking for was bt in Body_Type which tests if the string is within the list.
I want to make this code much more elegant, using loop for getting user input into a list and also making the list as a list of floats withot having to define each argument on the list as a float by itself when coming to use them or print them...
I am very new to python 3.x or python in general, this is the first code i have ever written so far so 'mercy me pardon!'
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n
if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
calc =list(range(2))
calc[0] = (input("number 1:"))
calc[1] = (input("number 2:"))
print (float(calc[0])/float(calc[1]))
Since you are saying you are new to Python, I'm going to suggest you experiment with a few methods yourself. This will be a nice learning experience. I'm not going to give you answers directly here, since that would defeat the purpose. I'm instead going to offer suggestions on where to get started.
Side note: it's great that you are using Python3. Python3.6 supports f-strings. This means you can replace the line with your print function as follows.
print(f"Hello {Name} What's up? "
"\nare you coming to the party tonight in {Place}"
"\n if not at least try to make simple calculator:")
Okay, you should look into the following in order:
for loops
List comprehension
Named Tuples
functions
ZeroDivisionError
Are you looking for something like this :
values=[float(i) for i in input().split()]
print(float(values[0])/float(values[1]))
output:
1 2
0.5
By using a function that does the input for you inside a list comprehension that constructs your 2 numbers:
def inputFloat(text):
inp = input(text) # input as text
try: # exception hadling for convert text to float
f = float(inp) # if someone inputs "Hallo" instead of a number float("Hallo") will
# throw an exception - this try: ... except: handles the exception
# by wrinting a message and calling inputFloat(text) again until a
# valid input was inputted which is then returned to the list comp
return f # we got a float, return it
except:
print("not a number!") # doofus maximus user ;) let him try again
return inputFloat(text) # recurse to get it again
The rest is from your code, changed is the list comp to handle the message and input-creation:
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n"+
" if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
# this list comprehension constructs a float list with a single message for ech input
calc = [inputFloat("number " + str(x+1)+":") for x in range(2)]
if (calc[1]): # 0 and empty list/sets/dicts/etc are considered False by default
print (float(calc[0])/float(calc[1]))
else:
print ("Unable to divide through 0")
Output:
"
Hello john What's up?
are you coming to the party tonight in Colorado
if not at least try to make simple calculator:
you will input 2 numbers now and i will devide them for you:
number 1:23456dsfg
not a number!
number 1:hrfgb
not a number!
number 1:3245
number 2:sfdhgsrth
not a number!
number 2:dfg
not a number!
number 2:5
649.0
"
Links:
try: ... except:
Lists & comprehensions
I have a function that I need to return back with the original question if there is text input rather than the number in the range given.
When I type in SER for instance to test the program it comes back with an error. I need a number to be input which relates to a given piece of code based on that number. How can I alter this?
def Choice(question):
choiceanswer=input(question)
if choiceanswer in range(1,6):
return choiceanswer
else:
return Choice(question)
loop = True
while loop:
DisplayMenu()
choiceanswer = Choice('Please make your choice:')
if choiceanswer == 1:
student = []
n = numberofstudentstoadd('How many students do you wish to add? You
can add between 1 and 5')
for count in range(0, n):
when I test this code the question for choice is reoccurring each time I put a number from the range in or it crashes/error message when I type text.
I need the program to run so that when I type 1-6 the number corresponds with the task I have asked it to do so for this instance 1 is to input student data. When text is input I need the question to reappear to make the user insert a number 1 to 6 based on the range. Hope this make better sense.
This is what is shown in the program:
MAIN MENU
1. Enter and store student details
2. Retrieve details of any student
3. Student List: Birthday Order
4. Student Email List
5. Full Student List
6. Exit
Please make your choice:e
Traceback (most recent call last):
File "E:\BCS\From desktop\Validation 3\tutor.py", line 84, in <module>
choiceanswer = Choice('Please make your choice:')
File "E:\BCS\From desktop\Validation 3\tutor.py", line 72, in Choice
choiceanswer=int(input(question))
ValueError: invalid literal for int() with base 10: 'e'
question for choice is reoccurring each time I put a number from the range
Well of course, you are not setting the loop variable to False anywhere, so the while condition is always positive.
it crashes/error message when I type text
That's because input function evaluates input as Python code. When you enter SER, it doesn't mean a string "SER", but a variable SER – and you end up with NameError.
You should use raw_input instead. Besides being the reason for your error, the input function is also quite dangerous. And actually, in Python 3, input is replaced with raw_input.
solution
Your code could look like this
def choose(question):
choiceanswer = raw_input(question)
if choiceanswer == 'SER':
global loop
loop = False
return
if int(choiceanswer) in range(1, 6):
return choiceanswer
else:
return choose(question)
loop = True
while loop:
...
Python isn't recognizing any number apart from 1 as an integer. When i enter a number to be multiplied the program will run the except ValueError even though i have entered an integer. This is the code i have.
Total = 0
Tsl = 100
receipt = open("Receipt.txt", "w")
while True:
try:
Prod_Code = input("Enter a code or Done to get your final receipt: ")
if len(Prod_Code) == 8:
int(Prod_Code)
with open("Data Base.txt", "r") as searchfile:
for line in searchfile:
if Prod_Code in line:
print(line)
Quantity = input("What quantity of this product do you want? ")
Total += float(line.split(",")[2] * int(Quantity))
print(Quantity)
print(Total)
receipt.write(line)
elif Prod_Code == "Done":
print("Bye Bye")
print(receipt)
receipt.close
exit()
else:
print("Incorrect length, try again")
except ValueError:
print("You must enter an integer")
The error occurs when i enter any other number than 1 when i enter the quantity. If anyone can see the problem any input will be appreciated
The problem is that
Total += float(line.split(",")[2] * int(Quantity))
multiplies the string line.split(",")[2] by the Quantity converted to integer. And then attempts to convert the resulting string to a float.
Eg, if line.split(",")[2] is '1.2' and Quantity is '3' then
line.split(",")[2] * int(Quantity)
results in '1.21.21.2', which can't be converted to float. :)
Instead do
Total += float(line.split(",")[2]) * int(Quantity)
BTW, you aren't actually closing the receipt file. You're just emitting the method name and discarding it. So change
receipt.close
to
receipt.close()
Even better: use with blocks to open all your files so they get closed automatically.
I should also mention that the plain exit() function is primarily intended for use in the interactive interpreter, and it's not guaranteed to exist in all environments. To ensure portability use sys.exit() instead. OTOH, it's not really needed here, you can just break out of that while loop.
One reason can be in inputing the Promo_Code , you are using input so if your promo code is abcdefgh then you must input it as 'abcdefgh' or "abcdefgh" because input in python 2 cannot take automatic decisions . For sake of simplicity always use raw_input() for inputting strings,
Also in your elif convert reciept.close to reciept.close().
I am quite behind on my coursework and I am stuck on developing my code for task 2.
My program must allow a user to enter a series of bar codes, search a text file for the codes and then, if found, ask the user for the quantity of the product they wish to purchase. Finally it should print a receipt of the total products bought and the total price.
However, my code does not work when I have to search for the code in my file, it just keeps looping and asking the user to enter their bar code again.
Here is my code so far:
loop=True
while loop==True:
print ("------STOCK LIST------")
print ("a - Place an order by barcode")
print ("b - Place an order by product name")
print ("x - Exit")
task=input("Please make your selection\n")
if task.lower()=="a":
print("------STOCK FILE LOADING------")
myfile=open("barcode.txt", "r") #this opens the text file
details=myfile.readlines() #reads the file and stores it as the variable 'details' #myfile.close() #closes the file
while True:
digits=input("Please enter your GTIN-8 code\n")
if len(digits) > 8 or len (digits) < 8: #if the digits are longer or shorter than 8 digits, the code is not accepted
print("Please enter a GTIN-8 code\n")
else:
break #if the code is the correct length, the loop ends
for line in details:
if digits in line:
productline=line
myfile=open("receipt.txt", "r") #opens receipt file
myfile.writelines("\n" + "+")
quantity=input("How much of the product do you wish to purchase?\n")
itemsplit=itemline.split(' ') #seperates into different words
price=float(itemsplit[2]) #price is
total=(price)*(quantity) #this works out the price
myfile.writelines("Your total spent on this product is: " +str("£:,.2f)".format(total)+"\n"))
else:
break
If you could help me I would be very grateful as none of my classmates will help me and if so, can you keep the code quite simple as I am not the best at coding?
I'm doing GCSEs myself right now so I appreciate the difficulty with coursework. Careful asking people for code though - I'm pretty sure that can get you disqualified in certain specifications (although I'm not doing the same as you).
I see two main problems in your code:
1. The indentation is incorrect (if I've correctly understood what you're trying to do)
I think it should be like this:
while loop==True:
print ("------STOCK LIST------")
print ("a - Place an order by barcode")
print ("b - Place an order by product name")
print ("x - Exit")
task=input("Please make your selection\n")
if task.lower()=="a":
print("------STOCK FILE LOADING------")
myfile=open("barcode.txt", "r") #this opens the text file
details=myfile.readlines() #reads the file and stores it as the variable 'details' #myfile.close() #closes the file
while True:
digits=input("Please enter your GTIN-8 code\n")
if len(digits) > 8 or len (digits) < 8: #if the digits are longer or shorter than 8 digits, the code is not accepted
print("Please enter a GTIN-8 code\n")
else:
break #if the code is the correct length, the loop ends
for line in details:
if digits in line:
productline=line
myfile=open("receipt.txt", "r") #opens receipt file
myfile.writelines("\n" + "+")
quantity=input("How much of the product do you wish to purchase?\n")
itemsplit=itemline.split(' ') #seperates into different words
price=float(itemsplit[2]) #price is
total=(price)*(quantity) #this works out the price
myfile.writelines("Your total spent on this product is: " +str("£:,.2f)".format(total)+"\n"))
else:
break
Right now, if the code inputted by the user is correct, you're breaking out of the entire while loop as soon as the code is validated. The program does not have time to do the next steps in the for loop.
2. The second if statement
if len(digits) > 8 or len (digits) < 8: #if the digits are longer or shorter than 8 digits, the code is not accepted
print("Please enter a GTIN-8 code\n")
else:
This can be made better. You can write a new if statement instead so that it breaks the while loop only if the code entered is the correct length.
Your current statement asks me to re-input the code twice every time I get it wrong, rather than only asking me once each time I input something incorrect.
I'm about to go work on your other question.
Good luck!