Python isn't recognizing integers apart from 1 - python

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().

Related

why is the return of the program not good?

I'm new to python and there's a video on Youtube that I watched. I do the exact same code as he but mine doesn't work and I don' understand why.
Here's the code:
MAX_LINES = 3
def deposit():
while True:
amount = input("What would you like to deposit? $")
if amount.isdigit():
amount = int(amount)
if amount > 0:
break
else:
print("Amount must be greater than 0. ")
else:
print("Please enter a number. ")
return amount
def get_number_of_lines():
while True:
lines = input("Enter the number of lines to bet on (1-" + str(MAX_LINES) + ")? ")
if lines.isdigit():
lines = int(lines)
if 1 <= lines <= MAX_LINES:
break
else:
print("Please enter a valid number of lines. ")
else:
print("Please enter a number. ")
return lines
There are 3 problems.
Unindent amount does not match previous indent. I have no idea what does that mean
"return" can be used only within a function. As far as I'm concerned I'm using it in the function, copied the first function then pasted it into the second function and somehow it doesn't work
"lines" is not defined. What dou you mean it's not defined, I define it in the first line of the function
https://www.youtube.com/watch?v=th4OBktqK1I
This video's code what I'm trying to do
I appreciate any help!
I just simply don't understand why it works in one and not the other
You have one space too much in front of while True in function get_number_of_lines().
Yes used in functions to return value
Because function don't get inside while loop (because of indent problem), lines is never defined, probably this was the problem.
So try fix indent and run again

Can someone explain why var = input() in python doesn't work?

You want to know your grade in Computer Science, so write a program
that continuously takes grades between 0 and 100 to standard input
until you input "stop", at which point it should print your average to
standard output.
NOTE: When reading the input, do not display a prompt for the user.
Use the input() function with no prompt string. Here is an example:
grade = input()
grade = input()
count = 0
sum = 0
while grade != "stop":
grade = input()
sum += int(grade)
count += 1
print(sum / count)
Please dont solve it for me, but if you can point out why setting grade as "input()" doesnt work
You input a line as the first operation and then correctly enter the loop only if it isn't "stop".
However, that should then be the value you use for summing rather than immediately asking the user for another value. In your current code, if the user enters "stop", there is no check before attempting to treat it as a number.
So, if you don't want a solution, I'd suggest you stop reading at this point :-)
Couldn't resist, could you? :-)
The solution is to simply move the second input call to the bottom of the loop, not the top. This will do the check on the last thing entered, be that before the loop starts or after the value has been checked and accumulated.
In addition, your print statement is inside the loop where it will print after every entry. It would be better
There's other things you may want to consider as well, such as:
moving your print outside the loop since currently you print a line for every input value. You'll also have to catch the possibility that you may divide by zero (if the first thing entered was "stop").
handling non-numeric input that isn't "stop";
handling numeric input outside the 0..100 range.
Don't use this since you're trying to educate yourself (kudos on you "please don't solve it for me" comment by the way) and educators will check sites like SO for plagiarism, but a more robust solution could start with something like:
# Init stuff needed for calculating mean.
(count, total) = (0, 0)
#Get first grade, start processing unless stop.
grade = input()
while grade != "stop":
# Convert to number and accumulate, invalid number (or
# out of range one) will cause exception and not accumulate.
try:
current = int(grade)
if current < 0 or current > 100:
throw("range")
# Only reaches here if number valid.
total += int(grade)
count += 1
except:
print(f'Invalid input: {grade}, try again')
# Get next grade and check again at loop start.
grade = input()
# If we entered at least one valid number, report mean.
if count > 0:
print(total / count)
the first input does not work, covered by the second input;
when input is "stop", int("stop") is wrong;
When reading the input, do not display a prompt for the user. you should print the ans after the while loop
you can use endless loop and break to solve this problem.
...
while True:
grade = input()
if grade == 'stop':
break
...
print(ans)

How to get this pseudocode to double a number in a while loop?

pseudocode
numtodouble=int
result=int
print("")
print("Enter a number you would like to double and press Enter.")
input (numtodouble)
<class 'int'>2
'2'
while numtodouble>0:
result=numtodouble*2
print("2 X", numtodouble, "=", result)
print("")
print("Enter a number you would like to double and press Enter.")
input(numtodouble)
break
print("OK, you entered a value <=0, ending execution.")
Does anyone know where I went wrong with my code? I've been struggling with this for hours.
try:
# input is stored as num_to_double. the input is cast to an int, and the string in input is the prompt
num_to_double = int(input("Enter a number you would like to double and press Enter."))
while num_to_double>0:
result=num_to_double*2
# Format puts the arguments into the curly braces in the order given
print("2 X {} = {}\n".format(num_to_double, result))
# input is cast to int and stored in num_to_double. The text in the input command is the prompt
num_to_double =int(input("Enter a number you would like to double and press Enter."))
# This is otuside the while loop, so this runs when the while loop breaks. The previous break command was making
# the code act not as intended
print("OK, you entered a value <=0, ending execution.")
# This catches if someone inputs a value that is not able to be cast to a string. It's the second half of the Try:
# Except block.
except ValueError as _:
print("A not-a-number was supplied")
This code is far simplier and does what you're trying to do. I assume you're learning python, so some of these things are not the simplest way to do things, like the format function, but are super useful to learn.
num_to_double = 0
result = 0
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
while num_to_double > 0:
result = num_to_double * 2
print("2 X {} = {}".format(num_to_double, result))
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
print("OK< you entered a value <=0, ending execution.")
This code is the closest I could do to the pseudocode provided. Declaring variables before they're used here isn't necessary and is messy. It's like the pseudocode wasn't meant to become python. Same with printing blank lines, those should be wrapped into the previous or next print lines.

Searching a text file for a string

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!

python - breaking out of nested conditional to top of original loop

I'm having issues with this part of my code:
if(input not in status_list):
print("Invalid Entry, try again.")
break
The break exits the whole program, I just want to go back to the beginning of the program (to while(1):) I've tried pass, continue, return can't think of anything else.. can anyone help??
Thanks :)
Also it's reading this variable income as a string still..: income = int(input("Enter taxable income: ")) The error message I get is "TypeError: 'str' object is not callable"
import subprocess
status_list = ["s","mj","ms","h"]
while(1):
print ("\nCompute income tax: \n")
print ("Status' are formatted as: ")
print ("s = single \n mj = married and filing jointly \n ms = married and filing seperately \n h = head of household \n q = quit\n")
input = input("Enter status: ")
if(input == 'q'):
print("Quitting program.")
break
if(input not in status_list):
print("Invalid Entry, try again.")
break
income = int(input("Enter taxable income: "))
income.replace("$","")
income.replace(",","")
#passing input to perl files
if(input == 's'):
subprocess.call("single.pl")
elif(input == 'mj'):
subprocess.call("mj.pl", income)
elif(input == 'ms'):
subprocess.call("ms.pl", income)
else:
subprocess.call("head.pl", income)
input = input("Enter status: ")
You rebind the name input from the input function to its result, which is a string. So the next time you call it, after continue does its work, input doesn't name a function any more, it's just a string, and you can't call a string, hence
TypeError: 'str' object is not callable
Use continue, and change your variable name so as not to clobber the function.
Your problem isn't continue, it's that you have an unresolved error further down in your code. Continue is doing exactly what it's supposed to (i.e. you want continue in that conditional).
You're renaming input as a string, so the name no longer points to the builtin input function in your code. This is why you don't use reserved keywords as variable names. Call your variable something other than "input" and your code should work fine.
Continue is working correctly. The problem with your script is that you're trying to call replace() on an int:
income = int(input("Enter taxable income: "))
# income is an int, not a string, so the following fails
income.replace("$","")
You can do something like this instead:
income = int(input("Enter taxable income: ").replace("$", "").replace(",", ""))

Categories

Resources