Encountered "EOFError: EOF when reading a line" on PythonAnywhere - python

I was trying to run a script in PythonAnywhere (this is my first time using it), but it said my code had an EOF error. When I run it in flask_app.py, it works, but when I refresh the website and try it on the site itself, it gives me this error.
Error running WSGI application
EOFError: EOF when reading a line
File "/var/www/samtheconqueror_pythonanywhere_com_wsgi.py", line 16, in <module>
from flask_app import app as application # noqa
File "/home/SamtheConqueror/mysite/flask_app.py", line 11, in <module>
IVI = float(input("Enter the initial value of investment: "))
Is this because I am using flask?
I am trying to calculate the return on investment in the script.
Here is the code:
Num = 0
IVI = 0
FVI = 0
Dvi = 0
Com = 0
age = 0
loop1 = True
while loop1:
try:
IVI = float(input("Enter the initial value of investment: "))
loop1 = False
except ValueError:
print("Invalid.")
print("")
loop2 = True
while loop2:
try:
FVI = float(input("Enter the final value of investment: "))
loop2 = False
except ValueError:
print("Invalid.")
print("")
loop3 = True
while loop3:
try:
Num = int(input("Enter the number of shares purchased: "))
loop3 = False
except ValueError:
print("Invalid.")
print("")
Cost = IVI * Num
loop4 = True
while loop4:
try:
Dvi = float(input("Enter amount earned from dividends: "))
loop4 = False
except ValueError:
print("Invalid.")
print("")
loop5 = True
while loop5:
try:
Com = float(input("Enter the amount spent on commissions: "))
loop5 = False
except ValueError:
print("Invalid.")
ROI1 = (FVI - IVI) * Num + Dvi - Com
ROI2 = ROI1 / (IVI * Num)
ROI3 = ROI2 * 100
print(ROI3)
print_value = str(ROI3)
print("")
print("ROI = " + print_value + "%")
print("")
t_f = input("Calculate Annualized ROI(t/f)?")
loop6 = True
while loop6:
if t_f == "t":
loop6 = False
pass
elif t_f == "f":
exit()
else:
print("Invalid")
print("")
loop7 = True
while loop7:
try:
age = float(input("Enter number of years you have held this investment for: "))
loop7 = False
except ValueError:
print("Invalid.")
print("")
years = 1 / age
aROI = (1 + ROI2)
aROI0 = pow(aROI, years)
aROI1 = (aROI0 - 1) * 100
print_value2 = str(aROI1)
print("Annualized ROI = " + print_value2 + "%")

Related

Binary search gets stuck

As a computer science student we were given an assignment to do binary search in python. I don't know what's wrong with my code everything seems just fine
when the searched item is in the middle everything works just fine but whenever I enter a different index position it gets stuck in the while loop.
def binary_search():
ordered_list = [0,1,2,3,4,5,6,7,8,9]
lower_bound = 0
upper_bound = 10
index = int((lower_bound + upper_bound) / 2)
item_f = int(input("please enter the number you want to find (1-10): "))
t = True
while t:
if ordered_list[index] == item_f:
print(f"number {item_f} is found at index position {index}")
t = False
elif item_f > ordered_list[index]:
lower_bound = index + 1
elif item_f < ordered_list[index]:
lower_bound = index - 1
if t == False:
print("number found")
else:
pass
binary_search()
I have added 1 line of code, please check it should working
def binary_search()
ordered_list = [0,1,2,3,4,5,6,7,8,9]
lower_bound = 0
upper_bound = 10
index = int((lower_bound + upper_bound) / 2)
item_f = int(input("please enter the number you want to find (1-10): "))
t = True
while t:
if ordered_list[index] == item_f:
print(f"number {item_f} is found at index position {index}")
t = False
elif item_f > ordered_list[index]:
lower_bound = index + 1
elif item_f < ordered_list[index]:
upper_bound = index - 1#Edit line
index = int((lower_bound + upper_bound) / 2) #Added line
if t == False:
print("number found")
else:
pass
binary_search()

How to better implement a history of user action?

I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()

Syntax Error while trying to display user inputed salaries within a range of the mean

This is the module that will input a two-dimensional array containing employee names and their corresponding salaries
salary = []
names = []
def floatInput():
done = False
while not done:
nameIn = input("Please enter the employee name or * to finish: ")
salaryIn = input("Please enter the salary in thousands for " + nameIn + ": ")
try:
salaryIn = float(salaryIn)
except:
print("I was expecting a positive floating point number!")
if nameIn == "*":
done = True
else:
salary.append(salaryIn)
names.append(nameIn)
return salaryIn
return nameIn
floatInput()
here I use a for loop to print and iterate through the list of names and salaries.
for i in range(len(names)):
print(names[i] + ", " + str(salary[i]))
Here I find the mean of the salaries.
def salaryMean():
mean = sum(salary) / float(len(salary))
print("The mean of the salaries is: " + str(mean))
return mean
salaryMean()
here I convert the salary to thousands.
for i in range(len(names)):
salary = salary[i] * 1000
Here I display all employees who earn within a range of $5,000 from the mean
This where I am getting a syntax error. Please help.
def displayNames():
done = False
x = 0
while not done:
if salary[x] >= (mean - 5000) and salary[x] <= (mean + 5000)
print(salary[x])
x += 1
if x > len(salary)
done = True
displayNames()
Try this:
def displayNames():
done = False
x = 0
while not done:
if done:
break
if salary[x] >= (mean - 5000) and salary[x] <= (mean + 5000):
print(salary[x])
x += 1
if x > len(salary):
done = True
displayNames()

Why can't 'tm' be registered as a variable out side the if statement?

run = 1
list1 = []
for i in range(2):
while run > 0 :
print("-------------------------------------------------------")
run = 1
reg_num = input("Registration Number in caps: ")
tsh = int(input("Hour Entered : "))
tsm = int(input("Minute Entered : "))
tss = int(input("Second Entered : "))
print("")
teh = int(input("Hour Exited : "))
tem = int(input("Minute Exited : "))
tes = int(input("Second Exited : "))
print("Time Entered (camera1)", tsh, ":", tsm, ":", tss, "and Time Exited (camera2)", teh, ":", tem, ":", tes)
if tsh < teh:
tm = (((teh - tsh)*60) + (tem - tsm) +((tes - tss)/60))/60
elif tsh > teh:
teh = 24 + teh
tm = (((teh - tsh)*60) + (tem - tsm) +((tes - tss)/60))/60
speed = run/tm
print("speed of", reg_num, "is", "{:.2f}".format(speed), "mph")
if speed > 70:
list1.append(reg_num)
break
print("Overspeeding vehicles are: ")
for item in list1:
print (item)
this is the code to calculate the speed of a vehicle that passes through a speed camera set 1 mile apart. i have to out put a list of vehicles that are exceeding the speed limit. the problem is when the code calculates the speed (speed = run/time) the error massage states that "tm"(totalminutes) is not defined. can you make some corrections and tell me what is wrong.
The problem is none of your conditions in the 'if' statement are met.
if tsh = teh:
tm = bla
elif tsh < teh:
tm = bla * 2
else:
tm = bla / 2 # Add the 'else' part to do something when all else fails.

How can i speed up this python code?

So I recently coded this as a little challenge to see how quick I could do it. Now since its working an such I want to speed it up. It finds all the proper devisors of a number, the highest proper devisor and times how long it all takes. The problem is with number like 5000 it takes 0.05 secs but with numbers like 99999999999 it takes 1567.98 secs.
this the old code I have made a new and improved version below
import time
def clearfile(name):
file = open(name + ".txt", "r")
filedata = file.read()
file.close()
text_file = open(name + ".txt", "w")
text_file.write("")
text_file.close()
def start():
num = input("Enter your Number: ")
check(num)
def check(num):
try:
intnum = int(num)
except ValueError:
error(error = "NON VALID NUMBER")
if(intnum < 0):
error(error = "POSITIVE NUMBERS ONLY")
else:
finddivisor(intnum)
def finddivisor(intnum):
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= intnum:
if (intnum % i) == 0:
print(i)
file = open("numbers.txt", "r")
filedata = file.read()
file.close()
text_file = open("numbers.txt", "w")
text_file.write(str(i) +"\n"+ filedata)
text_file.close()
i += 1
properdivisor(starttimer)
def properdivisor(starttimer):
file = open("numbers.txt", "r")
highest = file.readlines()
print("\nThe Highest Proper Divisor Is\n--------\n" + highest[1] + "--------" + "\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors.\n")
restart(errorrestart = "false")
def restart(errorrestart):
if errorrestart == "false":
input("Do You Want Restart?\nPress Enter To Restart Or Close The Programe To Leave")
start()
elif errorrestart == "true":
input("\nThere Was An Error Detected.\nPress Enter To Restart Or Close The Programe To Leave")
start()
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------")
restart(errorrestart = "true")
clearfile(name = "numbers")
start()
Can someone speed it up for me
EDIT 1
so after looking over it I have now edited it to be moving it away from a file to an array
import time
from array import *
def programme():
num = input("Enter your Number: ")
try:
intnum = int(num)
except ValueError:
error("NOT VALID NUMBER")
if(intnum < 0):
error("POSITIVE NUMBERS ONLY")
else:
numbers = array("i",[])
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= intnum:
if (intnum % i) == 0:
numbers.insert(0,i)
print(i)
i += 1
print("\nThe Highest Proper Divisor Is\n--------\n" + str(numbers[1]) + "\n--------" + "\n\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors.\n")
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------\n")
running = True
while(running == True):
programme()
print("----------------------------------")
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n----------------------------------")
else:
print("closing Down")
running = False
New Edit
import time, math
from array import *
def programme():
num = input("Enter your Number: ")
try:
intnum = int(num)
if(intnum < 0):
error("POSITIVE NUMBERS ONLY")
else:
numbers = array("i",[])
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= math.sqrt(intnum):
if (intnum % i) == 0:
numbers.insert(0,i)
numbers.insert(0,int(intnum/i))
print(i,":", int(intnum/i))
i += 1
numbers = sorted(numbers, reverse = True)
print("The Highest Proper Divisor Is\n--------\n",str(numbers[1]) , "\n--------\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors." )
except ValueError:
error("NOT VALID NUMBER")
except OverflowError:
error("NUMBER IS TO LARGE")
except:
error("UNKNOWN ERROR")
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------\n")
running = True
while(running):
programme()
print("----------------------------------")
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n----------------------------------")
else:
print("closing Down")
running = False
If you have divisor a of number n then you can tell one more divisor of n b = n / a. Moreover if a <= sqrt(n) then b >= sqrt(n) and vice versa. It means in your finddivisor function you can iterate while i * i <= n and print both divisors i and n / i.
By the way, you shouldn't open, read and close files in cycle. Open it once before cycle and close after if you need to read/write several times.
You don't need to read and rewrite the entire file every time you want to put a single entry into it. You can just do it once when you know what change you want. Also you could just append to it. Maybe something like this:
def finddivisor(intnum):
starttimer = time.time()
print("\nThe divisors of your number are:")
divs = set()
for i in range(1, int(math.sqrt(intnum)) +1):
if intnum % i == 0:
print(i)
divs.add(i)
divs.add(intnum // i)
with open("numbers.txt", "a") as file:
file.writelines("{}\n".format(ln) for ln in sorted(divs, reverse=True))
also your program flow is building a very deep stack. Try and flatten it with something like
def start():
clearfile()
while True:
n = get_number()
starttimer = time.time()
finddivisor(n)
properdivisor(starttimer)
input("Press Enter To Restart Or Close The Programe To Leave")
in properdivisor you dont need to read the whole file either, you just need the first line. so maybe something like:
def properdivisor(starttimer):
with open(FILENAME, "r") as file:
highest = file.readline().strip()
print "\nThe Highest Proper Divisor Is"
print "--------%s--------" % highest
print "It took %0.2f seconds to finish finding the divisors.\n" % (time.time() - starttimer)
AFTER EDIT
Something like this is how I would do it, and it runs less then a second on my box:
import math
def get_divisors(n):
yield 1
sqroot = int(math.sqrt(n))
for x in xrange(2, sqroot):
if n % x == 0:
yield x
yield n / x
if sqroot**2 == n:
yield sqroot
divisors = sorted(get_divisors(999999999999))
print divisors

Categories