eval () Unexpected EOF while parsing - python

So I'm trying to get two inputs that separate usernames by credit hours and every time after I've exited the loop I get an unexpected EOF.
fresh = []
soph = []
jun = []
sen = []
def classify(cr, un):
if cr <= 27:
fresh.append(un)
print(un, 'is a freshman.\n')
elif 28 <= cr <= 56:
soph.append(un)
print(un, 'is a sophomore.\n')
elif 57 <= cr <= 84:
jun.append(un)
print(un, 'is a junior.\n')
elif cr >= 85:
sen.append(un)
print(un, 'is a senior\n')
def main():
un = input('Student: ')
cr = eval(input('Credits: '))
while un and cr != '':
un = input('Student: ')
cr = eval(input('Credits: '))
classify(cr, un)
Specifically the error I get is:
File "./class.py", line 58, in <module>
main()
File "./class.py", line 51, in main
cr = eval(input('Credits: '))
File "<string>", line 0
I'm not sure if it's related (or if it's just something I'm overlooking) but I have to enter through Credit in order to exit the loop. Shouldn't the loop exit after pressing enter when Student comes up due to the AND operator?
edit: added classify func. I don't think this is the problem though, I've tried removing it and it still brings me back to the EOF.

You shouldn't be using eval() to turn a string into an integer. Use int instead.
def main():
un = input('Student: ')
cr = input('Credits: ')
classify(int(cr), un)
while un and cr:
un = input('Student: ')
cr = input('Credits: ')
classify(int(cr), un)
Credits must still be entered even after skipping the student name because the while condition is only evaluated before going into the code block, not after every statement in the block. If you want it to stop immediately when the user skips the student or credit value, do this:
def main():
while 1:
un = input('Student: ')
if not un: break
cr = input('Credits: ')
if not cr: break
classify(int(cr), un)
And, of course, use input for Python 3, and raw_input for Python 2.

Related

How to open and edit a txt file in a while loop?

First, I'm very new to python and this college class I took has been very unhelpful so sorry in advance.
I have a text document with book names. I need to make the user input an option. Each option coinsides with either displqaying the text document, editing the text document, or just stopping the program. I have the last
one. I can display it out of a loop. But, if I try to do it in a loop It jsut doesn't do anything, no error, just nothing.
f = open("Books.txt")
for line in f:
print (line)
inp = ()
while inp != 3:
print("1 - Display, 2 - Add, 3 - Exit")
inp = input("Please select an option.")
inp = int(inp)
if inp == 1:
print (f)
You can do this by using tell() and seek() methods with file object (f)
Here is the code for it
f = open("Books.txt", "a+")
inp = 0
while inp != 3:
print("1 - Display, 2 - Add, 3 - Exit")
inp = input("Please select an option.")
inp = int(inp)
if inp == 1:
if f.tell() != 0:
f.seek(0)
for line in f:
if line.strip():
print (line.strip())
elif inp == 2:
book = input("What is your book name? ")
f.writelines(["\n"+book])
f.close()
The output of this is as follows
1 - Display, 2 - Add, 3 - Exit
Please select an option.1
HELLO
WORLD
TEST
1 - Display, 2 - Add, 3 - Exit
Please select an option.2
What is your book name? Test2
1 - Display, 2 - Add, 3 - Exit
Please select an option.1
HELLO
WORLD
TEST
Test2
1 - Display, 2 - Add, 3 - Exit
Please select an option.3
Code explanation as follows
Open the file with append mode with readable access (https://docs.python.org/3/library/functions.html#open)
The file cursor will be at EOF (End of File) in this case so you can easily append the new text to the file
When the input is 1 we first check the cursor location using tell() which returns the integer value of the number of bytes read and if it's not in the starting. We move the cursor at starting of the file using seek(0) (https://docs.python.org/3/tutorial/inputoutput.html)
Since there are could be empty lines containing only new line characters which we can filter out while printing and later print the text by again stripping off the white characters using the strip() method on the string because the print function automatically adds new line character
To write the line we need to pass a new character (line separator of course) and then the input name of the book
f = open("Books.txt", "r+")
inp = 0
while inp != 3:
print("1 - Display, 2 - Add, 3 - Exit")
inp = input("Please select an option.")
inp = int(inp)
if inp == 1:
for line in f:
print (line)
elif inp == 2:
book = input("What is your book name? ")
f.writelines(["\n"+book])
f.close()
exit()

IndexError: list index out of range when trying to work with a CSV

I am working with a CSV file for a program I am writing but I seem to be getting this error:
Traceback (most recent call last):
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 115, in <module>
actionQ()
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453`Material 2\Task 3\Task 3.py", line 111, in actionQ
gtinQuestion()
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 80, in gtinQuestion
quantityQuestion() #It will start the quantityQuestion subprogram.
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 52, in quantityQuestion
if float(row[3]) >= float(quantity):
IndexError: list index out of range`
I'm not quite sure how to approach it but I have never had this problem before. Initially, quantityQuestion was its own program but I have decided to place it with this other code for accessibility.
As a side note - I am unable to overwrite the third row so that the new stock can be updated in the CSV. (Any help on this is also appreciated).
Code:
import csv
import sys
global totalPrice
totalPrice = 0
addItem = ""
gtinNum = ""
quantity = 0
restart = ""
price = 0
receipt = open("receipt.txt", "w+")
restockTxt = open("restock.txt", "w+")
file = open("ChocolateCSV2.csv", "r")
def restart():
restart = input("Would you like to restart? Y/N")
if restart.lower() == "y":
actionQ()
else:
file.close()
print("Exiting program.")
sys.exit()
def priceSub(): #Defining the restart subprogram
priceQ = input("Would you like to add an item? Y/N") #Asks the user if they would like to add an item.
global totalPrice #Declaring totalPrice and making it global.
totalPrice = int(price) + totalPrice #Setting totalPrice to add the variable price to itself.
if priceQ.lower() == "y": #If statement that checks to see if the user has entered a "y".
gtinQuestion() #If it is true, it will start the gtinQuestion subprogram.
else: #Anything other than a "y" will do the following commands.
global receiptCont #Declaring the receipt content as a global variable.
receiptCont = receipt.read() #Reads the receipt.
receipt.close() #Closes the file.
print(receiptCont) #Prints the content of the receipt.
print("Total Price: " + "%.2f" % round(totalPrice, 2)) #Prints the totalPrice variable rounded to two decimal places.
restart()
def quantityQuestion(): #Defining the subprogram for the quantity.
quantity = input("How much would you like?") #Asks the user how much of the item they would like.
if quantity.isdigit() == False: #If statement to check whether or not the user has entered an integer or not.
quantityQuestion() #If they have not entered an integer, it will ask the question again.
global price #Declaring the variable price as a global variable.
price = "" #Setting price to an empty string.
with open("ChocolateCSV.csv", 'r') as file2:
for row in csv.reader(file2): #Loop that seperates each row in the CSV
if str(gtinNum) in row[0]: #If statement to check if the GTIN given by the user is in the CSV.
if float(row[3]) >= float(quantity):
receipt.write(str(row) + "\n") #If it is in one of the CSV rows, it will write the row to the text file.
receipt.write(str("- Quantity: " + quantity + "\n")) #It also writes the quantity given by the user.
price = float(row[2]) * int(quantity) #The price is the price given by the CSV file multiplied by the quantity.
receipt.write("- Price: " + str("%.2f" % round(price, 2)) + "\n") #The final price (after the multiplication) is written to the text file also.
updateStk = str(float(row[3]) - float(quantity))
row[3] = updateStk
file2w = open("ChocolateCSV2.csv", "w", newline = "")
writeCSV = csv.writer(file2w)
writeCSV.writerows(csvList)
file2w.close()
priceSub() #Starts the restart subprogram.
break #Breaks the loop.
elif float(row[3]) <= float(quantity):
print("There is not enough stock to allow you to purchase this item - Try again u nerd.")
gtinQuestion()
else:
print("The code entered could not be found - Please re-enter") #If it is not in the CSV it will print this error message.
gtinQuestion() #Starts the gtinQuestion subprogram.
def gtinQuestion(): #Defining the gtinQuestion subprogram.
global gtinNum #Declaring the gtinNum variable as global.
gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:") #Setting that variable to the initial question.
if gtinNum.isdigit() == False or len(gtinNum) != 8: #If the code given is not an integer or is not 8 digits long...
print("Please re-enter your GTIN-8 code - Reason: Invalid Code") #It will print this error message and ask the question again.
gtinQuestion()
elif gtinNum.isdigit() == True and len(gtinNum) == 8: #If it is an integer and is 8 digits long...
quantityQuestion() #It will start the quantityQuestion subprogram.
def restockAction():
reader = csv.reader(file, delimiter = ",")
csvList = list(reader)
for row in csvList:
stDiff = float(row[5]) - float(row[3])
if float(row[3]) <= float(row[4]):
restockTxt.write(row[0]+" | "+row[1]+" | "+"Stock Replenished: "+(str(stDiff)+"\n"))
row[3] = row[5]
file2w = open("ChocolateCSV2.csv", "w", newline = "")
writeCSV = csv.writer(file2w)
writeCSV.writerows(csvList)
file2w.close()
else:
restockTxt.write("No (other) stock needs to be replenished.")
restockTxt.close()
restockRead = open("restock.txt", "r") print(restockRead.read())
restart()
def actionQ():
restock = input("What action would you like to perform?:\n Restock (Enter 1)\n Order (Enter 2)")
if restock == "1" or restock == "restock":
print("Restock Action Requested...")
restockAction()
elif restock == "2" or restock == "order":
print("Ordering action Requested...")
gtinQuestion()
else:
actionQ()
actionQ()
CSV File:
12312313 Item 1 0.5 100 25 100
12345670 Item 2 0.2 100 25 100
76543210 Item 3 0.3 100 25 100
34563670 Item 4 0.4 100 25 100

How to print output to text file from multiple functions (python)

I want to save the below code output to file.txt. The problem is that my code includes many functions.
In other words, I want my output in a text file, I'm using python but I posted as js, #python
import random
Generate_Number_CHOICE = 1
Average_Calculate_CHOICE = 2
Display_Grades_CHOICE = 3
Display_Failing_Marks_CHOICE = 4
QUIT_CHOICE = 5
def display_menu():
print(' MENU')
print('1) Enter Your Marks')
print('2) Get Your Average')
print('3) Display Your Grades')
print('4) Display Failin Marks')
print('5) Quit')
def generate_number():
numbers = random.sample(range(1 ,100),30)
print(numbers)
return numbers
def average_calculate(numbers):
total = sum(numbers)
average = total // 30
print('------------------------------------')
print('Your Average is:', average)
print(" ")
def display_grades(numbers):
for mark in(numbers):
if mark >= 90:
print('------------------------------------')
print('A+',mark)
elif mark >= 80:
print('------------------------------------')
print('B+',mark )
elif mark >= 70:
print('------------------------------------')
print('C+',mark)
elif mark >= 60:
print('------------------------------------')
print('D+',mark)
else:
print('------------------------------------')
print('F',mark)
return mark
return courses_Name
def display_failing(numbers):
for number in (numbers):
if number <= 59:
print('------------------------------------')
print("you Fail in",number)
print(" ")
def main():
infile = open('philosophers.txt', 'w')
choice = 0
while choice != QUIT_CHOICE:
display_menu()
choice = int(input('Enter your choice: '))
if choice == Generate_Number_CHOICE:
numbers = generate_number()
elif choice == Average_Calculate_CHOICE:
average_calculate(numbers)
elif choice == Display_Grades_CHOICE:
mark = display_grades(numbers)
elif choice == Display_Failing_Marks_CHOICE:
display_failing(numbers)
elif choice == QUIT_CHOICE:
print('Exiting the program...')
else:
print('Error: invalid selection.')
main()
You can just replace you print statements with infile.write('text goes here'), also don't forget to close your file after you're done with it using infile.close(). Alternately you can use a with statement.
with open('philosophers.txt', 'w') as infile:
infile.write('text')
and this will close the file without explicitly calling .close.
You can also print to a file
print('text', file=infile) #python 3
print >> infile, 'text' #python 2
You can open a file (as global variable) in the beginning of your main function and in all other functions use that file handle to write whatever you want in the file.But an even better solution is to pass that file handle to each function and use the handle to write to file. Either way, don't forget to close the file at the end of the main function.

How can I modify this code so it doesn't go back to the beginning of the function, but a little bit after the beginning?

I'm working on a school project and I have a problem. I have to write code for apothecary where clients can buy medicine. So, I need to make restrictions, which one doesn't go with others and etc. Here is the code:
def prodajLek():
lekovi = Fajl1.UcitavanjeLekova()
lekoviRed = []
brojacZaForPetlju = 1
n = 0
cena = 0
kolicina = []
korpa = []
rednibrojevilekova = []
ukupnacena = 0
print(" Fabricki naziv Genericki naziv Serijski broj Kolicina Cena \n")
for i in lekovi:
x = i.strip().split("|")
lekoviRed.append(x)
if lekoviRed[n][5] == "False":
print(brojacZaForPetlju,"\t {:10} \t {:10} \t\t\t {:3} \t\t\t {:4} \t\t {:5}".format(x[0],x[1],x[2],x[3],x[4]))
brojacZaForPetlju = brojacZaForPetlju + 1
n = n + 1
print("\n\n\n\n")
rednibrleka = input("Izaberite redni broj leka koji zelite da prodate:\n>>\t")
rednibrleka = int(rednibrleka)
rednibrleka = rednibrleka - 1
rednibrojevilekova.append(rednibrleka)
kolicinaZahteva = input("Koju kolicinu zelite da prodate?\n>>\t")
kolicinaZahteva = int(kolicinaZahteva)
if kolicinaZahteva > int(lekoviRed[rednibrleka][3]):
print("Nema toliko na lageru!\n")
Fajl1.LekarMenu()
kolicina.append(kolicinaZahteva)
cena = int(lekoviRed[rednibrleka][4])
korpa.append(cena)
print("Da li zelite da kupite jos lekova?\n1.Da\n2.Ne\n")
nastavakKupovine = input(">>")
if nastavakKupovine == "1":
prodajLek()
elif nastavakKupovine == "2":
Fajl1.LekarMenu()
So, when I get to the nastavakKupovine input, when I press 1, I need to continue shopping and store my row numbers, my price and quantity in arrays rednibrojlekova = [] , korpa = [] and kolicina = []. But I have a problem, because I dont know how to continue this without reseting these arrays to empty.
The standard idiom for what you want to do is a while True loop. Rather than show how to change your (rather long) function, here's a very simple one which hopefully shows the principle in a straightforward way:
def ask():
answers = []
while True:
response = input("What do you have to say? ")
answers.append(response)
check = input("Type 'q' to quit, anything else to repeat: ")
if check == "q":
break
else:
continue
return answers
For this simple function, the else: continue part isn't necessary, because the loop will continue anyway, but I've included it so you can see how to use it.
Here's an example of the function in action:
>>> ask()
What do you have to say? Something
Type 'q' to quit, anything else to repeat:
What do you have to say? Another thing
Type 'q' to quit, anything else to repeat:
What do you have to say? Ok, done
Type 'q' to quit, anything else to repeat: q
['Something', 'Another thing', 'Ok, done']
>>>
You can find out more about while, break and continue by reading the More Control Flow Tools chapter of the official Python tutorial.

wrapping text from a file

I am writing a program that will open a specified file then "wrap" all lines that are longer than a given line length and print the result on the screen.
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wr.width = lLength
wr.expand_tabs = True
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
print(wraped)
main()
When I do this instead of wrapping it prints everything in the file as a list with commas and brackets, instead of wrapping them.
textwrap.TextWrapper.wrap "returns a list of output lines, without final newlines."
You could either join them together with a linebreak
print('\n'.join(wrapped))
or iterate through and print them one at a time
for line in wrapped:
print(line)

Categories