I'm trying to have my input move on when enter is pushed on a line with only spaces or just a blank, it doesn't work though it gives me a value error once before it gives me the proper return, which in turn seems to append an extra value to my array and screws over the entire program.
import math
def getItems():
quitNow = False
while not quitNow:
prepTotal = []
paintTotal = []
priceTotal1 = []
priceTotal1d = []
priceTotal2 = []
priceTotal2d = []
names = []
loopQuit = False
index = 1
while not loopQuit:
ans = raw_input("Enter a Name and press Enter to Continue\nEnter \"Q\" to Quit and get the Full Price: ")
if(ans.lower() != "q"):
innerLoopQuit = False
names.append(ans)
print "\nPlease enter your prep hours for " + names[index-1] + ": "
while not innerLoopQuit:
try:
inp = raw_input()
if(inp == ""):
innerLoopQuit = True
else:
float(inp)
prepTotal.append(float(raw_input()))
except ValueError:
print "Please enter a valid number."
You're calling raw_input() again in your else clause. Also, float(inp) doesn't really do anything if you don't assign it anywhere. prepTotal.append(float(inp)) is what you want to do.
Related
I am writing a piece of python code that allows you to switch your default printer. It outputs the data of wmic printer list brief to a .json file and lists those printers out with an assigned number. If the input is not included in the numbers it throws an error to the user. If the user inputs a character instead of a number the conversion from string to int fails and I cannot get a try/except to catch the error. Any help would be awesome!
def setDefaultPrinter():
with open('resources/data.json') as json_file:
data = json.load(json_file)
loopvalue = 1
print('\n List of avalible printers: \n')
printerlist = []
error = False
for i in data:
print(str(loopvalue) + ". " + i)
loopvalue += 1
printerlist.append(i)
#any(printer in x for x in lst)
try:
global printer
printer = int(input("\nWhat printer do you want to use? (Number on the side): "))
except ValueError:
print("Please enter a number, not a letter")
error = True
except Exception:
print("Internal Error")
try:
if printer == None:
print("Error")
except Exception:
print("ERROR")
error = True
if printer <= len(printerlist) and not error:
printer = int(printer)
printervalue = printer - 1
printername = printerlist[printervalue]
print(printername)
else:
if error == False:
print("Invalid Responce")
def setDefaultPrinter():
with open('resources/data.json') as json_file:
data = json.load(json_file)
loopvalue = 1
print('\n List of avalible printers: \n')
printerlist = []
error = False
for i in data:
print(str(loopvalue) + ". " + i)
loopvalue += 1
printerlist.append(i)
#any(printer in x for x in lst)
printer = input("\nWhat printer do you want to use? (Number on the side): ")
if not printer.isdigit():
error = True
print("\nValue Error: Please Check Your Input")
if not error and int(printer) <= len(printerlist):
printer = int(printer)
printervalue = printer - 1
printername = printerlist[printervalue]
print(printername)
else:
if error == False:
print("Invalid Responce")
So i have this college python project that asks me to make a program to manage an inventory, my question basically is that whenever I try to convert the price and the quantity again to floats this exception rase, so how can I convert them so I can make further process on them?
note that I tried to use .strip but it didn't work
this is the error:
float_price = float(i)
ValueError: could not convert string to float: '.'
this is the code that I have issues with:
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
float_price = float(i)
price += float_price
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
this is the code to add data to the file:
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n' + make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to import the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+ '\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
as error message indicates '.' is string and it cannot be converted to float so raises error.. it depends what you want to do with such situation you can use try except as.
from tabulate import tabulate
def read_data():
file = open("inventory.txt", "r")
list_of_lists = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
updated_list = list_of_lists[1:]
file.close()
return updated_list
def list_data():
updated_list = read_data()
index = 0
price = 0
quantity = 0
j = 0
while j < len(updated_list):
for i in updated_list[1][4]:
try:
float_price = float(i)
price += float_price
except ValueError as e:
print('Value Error')
print(price)
header = ['MAKE', 'MODEL', 'PART ID', 'PART NAME', 'PRICE', 'QUANTITY']
print(tabulate(updated_list, headers=header))
list_data()
Trying to get this program to work for a school project, but in line 26 of the code I get an unsupported operand type error for 'int' and 'str'. Any help would be appreciated. Here is the code:
final = False
while final == False:
while True:
try:
eventName = str(input("What is the event's name? "))
numberJudges = int(input("How many judges are there? "))
competitorName = str(input("What is the competitor's name? "))
judgeScores = input("Please enter the judges scores with a space between each one. ")
break
except ValueError:
print("That is not a valid name or number(s)")
finalJudges = numberJudges - 2
def judgeScoreListFunction(judgeScores):
judgeScoreList = judgeScores.split()
return judgeScoreList
def cleanJudgeScoresFunction(judgeScoreList):
judgeScoreList.remove(max(judgeScoreList))
judgeScoreList.remove(min(judgeScoreList))
finalJudgeScores = judgeScoreList
return finalJudgeScores
def cleanScoreFunction(finalJudgeScores, finalJudges):
cleanedScore = sum(finalJudgeScores)
finalScore = cleanedScore / finalJudges
format(finalScore, '.2f')
return finalScore
judgeScoreList = judgeScoreListFunction(judgeScores)
finalJudgeScores = cleanJudgeScoresFunction(judgeScoreList)
finalScore = cleanScoreFunction(finalJudgeScores, finalJudges)
if competitorName == "Finish":
final = True
Instead of:
judgeScoreList = judgeScores.split()
You want:
judgeScoreList = [int(X) for X in judgeScores.split()]
I'd also recommend getting rid of all these little single-purpose functions.
my program keeps throwing up a syntax error with no reason given with this code and I cannot figure out why for the life of me. I've deduced that the error-causing lines are the ones I have hashed-out
#char = ord(message[i])-96
#key = ord(keyword[i])-96
They are in lines 15 and 16 of the code. Please help me!!!
option = input("Do you want to encrypt or decrypt? (E/D): ")
keyword = input("Enter your keyword: ")
message = input("Enter your message: ")
while len(keyword)<len(message):
keyword=keyword+keyword
keyword=keyword[:len(message)]
newMessage = ""
for i in range(len(message)):
char = ord(message[i])
key = ord(keyword[i])
if char==32:
newMessage = newMessage+" "
elif char<97 or char>122:
message = input("Enter your message: ")
#char = ord(message[i])-96
#key = ord(keyword[i])-96
elif option == "E":
if char+key>26:
newMessage = newMessage+chr(char+key-26)
else:
newMessage = newMessage+chr(char+key)
else:
if char-key<1:
newMessage = newMessage+chr(char-key+26)
else:
newMessage = newMessage+chr(char-key)
print(newMessage)
You are ending your if and subsequent elif with those two lines. As a result, elif option == "E": makes no sense as there is no preceding if statement before it. You either have to indent:
elif char<97 or char>122:
message = input("Enter your message: ")
char = ord(message[i])-96
key = ord(keyword[i])-96
Or begin a new if statement with your subsequent elif:
if option == "E":
if char+key>26:
newMessage = newMessage+chr(char+key-26)
else:
newMessage = newMessage+chr(char+key)
You have not indented (put 4 space before) the two lines. As your are in a if statement you have to put them.
# Let's create a file and write it to disk.
filename = "test.dat"
# Let's create some data:
done = 0
namelist = []
while not done:
name = raw_input("Enter a name:")
if type(name) == type(""):
namelist.append(name)
else:
break
For the Python code above, I tried, but could not break from the while loop. It always asks me to "Enter a name:", whatever I input.
How to break from the loop?
# Let's create a file and write it to disk.
filename = "test.dat"
# Let's create some data:
namelist = []
while True:
name = raw_input("Enter a name:")
if name:
namelist.append(name)
else:
break
This breaks when entered nothing
This is because raw_input always returns a string, i.e., type(name) == type("") is always true. Try:
while True:
name = raw_input("Enter a name: ")
if not name:
break
...