#app.route('/')
def index():
tpopDloads = popDloads
tpopShipped = popShipped
locPopDload = []
locPopShipped = []
popDinfo = []
popSinfo = []
popDloadsOrd = sorted(tpopDloads, reverse=True)
popShippedOrd = sorted(tpopShipped, reverse=True)
for i in range(3):
locPopDload.append(tpopDloads.index(popDloadsOrd[i]))
popDinfo.append(dProducts[locPopDload[i]])
tpopDloads[tpopDloads.index(popDloadsOrd[i])] = -1 #Problem line#
for i in range(3):
locPopShipped.append(tpopShipped.index(popShippedOrd[i]))
popSinfo.append(sProducts[locPopShipped[i]])
tpopShipped[tpopShipped.index(popDloadsOrd[i])] = -1
return render_template('index.html', popDinfo=popDinfo, popSinfo=popSinfo)
The error I'm getting is:
File "/var/lib/openshift/5697165a0c1e66eb870000fb/app-root/runtime /repo/flaskapp.py", line 47, in index
tpopShipped[tpopShipped.index(popDloadsOrd[i])] = -1
ValueError: 0 is not in list
This is using two variable that are popDloads and popShipped which are both lists that contain a set of integers. I don't see why it's not working as it is trying to find the actual index of a number after the list has been ordered. It also works when the numbers are all zero, it's only after I change the numbers in another piece of code that I run into problems.
The error is telling you why your code isn't working. 0 isn't in the list tpopShipped.
>>> [1,2,3].index(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 0 is not in list
Related
My function:
def buttons_for_country(main_master,datasets):
country_list = every_country_in_datasets(datasets)
rows = 0
columns = 0
for i in range(1,len(country_list)):
name = "button",i
name = tkinter.Button(master = main_master,
command = lambda: plot(10000)
height = 2,
width=10,
text=country_list[i-1])
if rows == 12:
rows = 0
colums += 1
name.grid(rows,columns)
rows += 1
name.pack()
It cames error at name.grid(rows,columns) said:
Traceback (most recent call last):
File "c:/Python/Covid/Cov_predict.py", line 93, in <module>
buttons_for_country(window,df)
File "c:/Python/Covid/Cov_predict.py", line 75, in buttons_for_country
name.grid(rows,columns)
TypeError: grid_configure() takes from 1 to 2 positional arguments but 3 were given
It seems fine with by giving 2 params rows and columns
But it said i given 3 paramsWhere do i did wrong here?
You should specify the row and column as keyword arguments.
name.grid(row=rows, column=columns)
You also need to remove name.pack() - a widget can only be controlled by a single geometry manager, and the last one you use is the one that is in control. Calling pack() after calling grid() removes all of the benefits of calling grid().
I want to accept different data types from user using list comprehension in python 3
This is my code with for loop -
stuRecords = []
for i in range(1, num+1):
print('Enter the name and marks of {} student.'.format(i))
name = input()
marks = int(input())
stuRecords.append([name,marks])
How can I write this code using list comprehension. I have tried this -
stuRecords = [[name,marks] for name,marks in input(f'\nEnter the name and
marks of {num} students').strip().split()][:num]
But I get this error -
Enter the name and marks of 2 students...John
Traceback (most recent call last):
File "HR_NestedList.py", line 13, in <module>
stuRecords = [[name,marks] for name,marks in input(f'\nEnter the name and marks of {num} students...').strip().split()][:num]
File "HR_NestedList.py", line 13, in <listcomp>
stuRecords = [[name,marks] for name,marks in input(f'\nEnter the name and marks of {num} students...').strip().split()][:num]
ValueError: too many values to unpack (expected 2)
Try this :
num = 3
stuRecords = [[[name, int(marks)] for name, marks in
[input(f'Enter the name and marks of {i}th students:\n').strip().split()]][0]
for i in range(1, num+1)]
print(stuRecords)
I would like to import the list from the file, read it line by line (already works). Each line containing a string representing a list.
I have to execute couple of tasks on it, however I got twisted and I dont know why below doesn't work. It gives me the following error :
ErrorCode:
Traceback (most recent call last):
File "main.py", line 8, in <module>
if len(n) != len(str(n + 1)):
TypeError: must be str, not int
f = open('listy.txt', 'r')
content = f.read().split('\n')
for n in content:
n.split(',')
## checking lengh
if len(n) != len(str(n + 1)):
print('Different lengh')
else:
print('All fine.')
Change
n.split(',')
if len(n) != len(str(n + 1)):
to:
n = n.split(',')
len(n[0]) != len(n[1]):
and don't forget to close your file with a f.close()
Better even, use with, example:
with open('listy.txt', 'r') as f:
content = f.read().split('\n')
you do not need a close() method when using with
I am new to python3 and tring to build a sqlobject class which named whatever. Then I created a function to caculate the average of one column. Here are parts of the codes.
class whatever(sqlobject.SQLObject):
_connection = connection
f1 = sqlobject.FloatCol()
f2 = sqlobject.FloatCol()
wid=sqlobject.IntCol(default=None)
def avg(col, num):
l1 = []
for i in range(1,num):
e = whatever.get(i).col
l1.append(a)
return statistics.mean(l1)
print (avg(f1, 5))
But it returns the error:
Traceback (most recent call last):
File "test1.py", line 58, in <module>
print (avg(f1, 5))
NameError: name 'f1' is not defined
However, when I directly wrote down the code like this:
class whatever(sqlobject.SQLObject):
_connection = connection
f1 = sqlobject.FloatCol()
f2 = sqlobject.FloatCol()
wid=sqlobject.IntCol(default=None)
l1 = []
for i in range(1,5):
e = whatever.get(i).f1
l1.append(e)
print (statistics.mean(l1))
It works fine. So what should I do with the def avg(col, num) function?
Please note that whatever.get(i).f1 works — this because you name the column explicitly. If you want to get a column by name you have to:
pass the name of the column, i.e. avg('f1', 5);
get the value for the column using getattr.
So the fixed code is:
def avg(col, num):
l1 = []
for i in range(1, num):
e = getattr(whatever.get(i), col)
l1.append(a)
return statistics.mean(l1)
print(avg('f1', 5))
PS. The next error in your code will be NameError: a. What is a? Do you mean e?
I'm trying to make a program that will pick up randomly a name from a file. The user would be asked if he wants to pick up another one again (by pressing 1).
The names can't be picked up twice.
Once picked up, the names would be stocked in a list, written into a file.
When all the names are picked up, the program would be able to restart from the beginning.
I checked other similar problems, but I still don't get it...
from random import *
#import a list of name from a txt file
def getL1():
l1 = open("Employees.txt", "r")
list1 = []
x = 0
for line in l1:
list1.append(line)
x = x+1
list1 = [el.replace('\n', '') for el in list1]
#print("list" 1 :",list)
return list1
#import an empty list (that will be filled by tested employees) during
#execution of the program
def getL2():
l2 = open("tested.txt", "r")
list2 = []
for line in l2:
list2.append(line)
list2 = [el.replace('\n', '') for el in list2]
#print("list 2 :",list2)
l2.close()
return list2
def listCompare():
employees = getL1()#acquire first list from employee file
tested = getL2()#acquire second list from tested file
notTested = []# declare list to hole the results of the compare
for val in employees:
if val not in tested: #find employee values not present in tested
#print(val)
notTested.append(val)#append value to the notTested list
return notTested
def listCount():
x=0
employees = getL1()
tested = getL2()
for val in employees:
if val not in tested:
x = x+1
return x
#add the names of tested employees the the second second file
def addTested(x):
appendFile = open("tested.txt", "a")
appenFile.write(x)
appendFile.write('\n')
appendFile.close()
def main():
entry = 1
while entry == 1:
pickFrom = listCompare()
if listCount() > 0:
y = randint (0, (listCount ()-1))
print ('\n' + "Random Employee to be tested is: ", pickFrom(y), "\n")
addTested(pickFrom[y])
try:
entry = int(input("Would you like to test another employee? Enter 1:"))
except:
print("The entry must be a number")
entry = 0
else:
print("\n/\ new cycle has begun")
wipeFile = open("tested.txt", "w")
print ("goodbye")
main()
The last error that I have is :
Traceback (most recent call last):
File "prog.py", line 78, in <module>
main()
File "prog.py", line 65, in main
print ('\n' + "Random Employee to be tested is: ", pickFrom(y), "\n")
TypeError: 'list' object is not callable
As per the code print pickFrom is a list and when you are referencing it in the print it needs to be called using [ ]. Change it to pickFrom[y]