so as i have written in title i have problem with 2 things, mainly i want to add values in to a list and dont delete already existing, but i cant figure out how to do it, for now when im writing something everything old gets deleted. My second problem is that i cant make condition to use upper letter T and lower t, can anyone help me? here is the code:
import pickle
zadania = []
a = input("Do you want to add value? T/N")
while True:
if a == 'T':
zadania.append(str(input('Write what you want to add: ')))
a = input("Do you want add something else? T/N")
elif a == 'N':
break
else:
while a not in 'TN':
print("Wrong value")
a = input("Do you want add something else? T/N")
with open('zad', 'wb') as fp:
pickle.dump(zadania, fp)
zadania = []
This always starts with an empty list. If you don't want that, then you should do something different. For example, you could check if the file you wrote before already exists. If it does, load it before getting more items.
For lower and upper case you could use if check as follows:
if a.lower()=="t":
pass
OR
if a.upper()=="T":
pass
Regarding list, your list is adding new element in existing list.
But if you are loading your list from pickle then you should first initialize zadania to pickle value and not directly [] empty. If pickle is not having any value then assign [] else pickle value.
Related
I'm writing a code as a "checklist" for something that is to be made.
each line is basically:
a0=int(input(f'do step one, then enter 1 to cont')
a1=int(input(f'do step two, then enter 1 to cont')
So, how can I skip to line a4 (or a(n) ) and continue from there?
My thoughts were to define each line and store each variable in a list. Then use a while loop to start from wherever. I just can't figure out how to eh, this is where I lose it. I guess I'm trying to convert the string to a variable name, to define it from there. See below:
ail=len(ai) #where ai=[a0,a1,a2..]
a=0 #i would input a as any val.
while a in range (0,ail):
b=(f'a{a}') #this line would determine the "instruction line" to start from.
exec("%s = %d" % (b,b)) #this is the line that names a var from a string
b0=int(input(f'{b}'))
I suggest you use dictionary instead of list. you can access the elements of dictionary using keys and that is going to help you pick a specific spot to traverse from.
Dictionary keys
I am trying to make a program where my students will enter their ID numbers so I can (later in the code) automate sending attendance, and record who has handed in homework and who hasn't so emails can be sent to parents. I have everything else made, but I cannot get the inputting of student ID's working.
What I am trying to do:
1)make sure that their input is 7 characters long
2)check their ID exists in 'fakeID'
2a)have the students confirm their name from 'classNames' with a y/n.
2b) append their name into inputIDList
3) if the input is == to 9999990 exit the loop.
What it is doing:
1) asking for input
2) moving on in the code and not looping
3) not appending inputIDList
I think I am making this too complicated for my current skill level.
edit:
The loop is not checking to see if the inputed ID is in my fakeID list.
Also, it isnt looping for, so once the input is entered it continues on with the next set of code.
edit2:
updated code that works. :D
fakeID = ['1111111','1111112','1111113','1111114','1111115']
classNames = ['name1', 'name2', 'name3', 'name4', 'name5']
toplist = list(zip(fakeID, classNames))
inputIDList =[]
def inputID():
while True:
id = input('Please enter your student ID and hit Enter')
if id == '9999990':
print('Done')
break
if id in fakeID:
inputIDList.append(id)
print('recorder')
continue
if id not in fakeID:
print('I do not know this ID. Please try again.')
continue
If I understood your problem correctly then I suppose that you are trying to save the ID numbers of the students in inputIdList and then check whether a particular ID is in inputIdList or not. In the last if condition you are trying to compare a List type object with a String type object which will definitely throw an TypeError. Instead define the following function and call it in the if condition.
def check_list(id):
try:
inputIdList.index(id)
return True
except TypeError:
return False
list.index() method tries to find the element in the list and returns the index number of the element. And then call this function in your if condition.
if check_list('9999990'):
print('done')
#break
Furthermore there is no need to assign inputIdList = [""] if you have already intialized it to inputIdList = [].
If the problem persists please send the output in the thread.
Here is something to get you started:
fakeID = {'1111111','1111112','1111113','1111114','1111115'}
while True:
id = input('Please enter your student ID and hit Enter')
if id == '9999990':
print('Done')
break
if id not in fakeID:
print('I do not know this ID. Please try again.')
continue
as Abarnert said you need to restructure your method. but I think I found where you were stuck.
after you have checked for the length of input number, you should check whether that number matches any fakeID,and get the corresponding class name.
so your first loop should be like this
for i in toplist:
rather than
for i in [i for i,x in enumerate(inputIDList) if x == fakeID]:
since inputIDList is empty your program will not go inside the loop. And inside the changed loop you should be checking
if s == fakeID
This is the limit of what I could understand of your desired operation. But if you need further help just ask.
cheers.
I have a list of dictionaries called listCityStateZip. One of the keys in listCityStateZip is called cityStateZip. I want to see which of the cityStateZip values exist in a MongoDB collection called zipcodes (field: citystatezip). If no match is found, then I want to flag that record in my list as "N". If a match is found, I want to flag that record in my list as "Y". I thought the code below would address my issues, but for some reason only the very first record in listCityStateZip (the list) ends up getting a flag. Code shown below. Two questions: 1) is there an easier way to write this code using python and 2) if not, why do I get a flag only in the very first record in my list?
for a in listCityStateZip:
for b in db.zipcodes.find({'citystatezip': a['cityStateZip']},{'_id':1}):
c.append(b)
if len(c) == 0:
a['flag'] = 'N'
else:
a['flag'] = 'Y'
c=[]
You can try this, much easier way
for a in listCityStateZip:
if db.zipcodes.find({'citystatezip': a['cityStateZip']}).count() > 0:
a['flag'] = 'Y'
else:
a['flag'] = 'N'
Currently, I have a CSV file set out like this:
Element,Weight
"Hydrogen","1"
"Oxygen","16"
Eventually it'll have all of the elements and their atomic weights next to them, but putting all of that in is rather pointless unless I get this issue solved first.
The main Python program is as follows:
import csv
reader = csv.reader(open("chem.csv", "rb"))
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
if first == "Hydrogen" or "hydrogen":
for Weight in reader:
print Weight
else:
print "No."
Now, as you might be able to tell from that, my aim here is to have the program display the weight of hydrogen as taken from the CSV file, for now. However, currently it just ends up displaying the following:
Enter first element: hydrogen
Enter second element: oxygen
['Element', 'Weight']
['Hydrogen', '1']
['Oxygen', '16']
So, basically, how can I make it so that it goes to the Hydrogen row and then takes the weight value from the second column? I should be able to go from there to nail the rest of the program, but this part has got me stuck.
As a secondary thing, is it at all possible to have it so that I won't have to have what is essentially a list of elements in the main Python program as well as in the CSV file? It'd cut down a lot on the clutter, but I just can't get it figured out.
Instead of iterating over the data it is probably nicer to store it in an easy accessible way, e.g. a dictionary mapping name to weight. Then you can just do a look-up for the entered string and display the result (or not if there is none).
import csv
#Read in data anbd store it in dictionary.
#The element name will be stored in lowercase.
elemen_data = { element.lower():int(weight) for element,weight in csv.reader(open("in", "rb"))}
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
#Look for the weight of the entered element (after converting it to all lowercase)
weight_first = elemen_data.get(first.lower())
weight_second = elemen_data.get(second.lower())
if weight_first is not None:
print 'First Element:', first, 'Weight:', weight_first
else:
print 'First Element', first, 'not found'
if weight_second is not None:
print 'Second Element:', second, 'Weight:', weight_first
else:
print 'Second Element', second, 'not found'
Storing your data apart from you program logic can make sense if you want to be able to easily make changes to the data without touching the program. So having a csv-file that is read in is absolutely okay. (As long as the data has a reasonable size)
The problem is that when you iterate over csv.reader object you receive csv file rows as lists of your row cells values. So you can try next for your case:
if first in ("Hydrogen", "hydrogen"):
for Weight in reader:
if Weight[0] == first:
print Weight[1]
That's not the best code, but that returns the value you wanted.
First problem:
if first == "Hydrogen" or "hydrogen":
That won't return what you want. You either want:
if first == 'Hydrogen' or first == 'hydrogen':
or
if first in ['Hydrogen', 'hydrogen']:
Or better yet:
if first.lower() == 'hydrogen'
Which would work for all capitalizations, like HYDrogen.
Then, in that you can do what you want:
for row in reader:
if row[0].lower() == first.lower():
print row[1]
Of course, this could be cleaned up a bit by using a dictionary of values; you probably don't want an if statement for every element, but there you go.
I need to test if the user input is the same as an element of a list, right now I'm doing this:
cars = ("red", "yellow", "blue")
guess = str(input())
if guess == cars[1] or guess == cars[2]:
print("success!")
But I'm working with bigger lists and my if statement is growing a lot with all those checks, is there a way to reference multiple indexes something like:
if guess == cars[1] or cars[2]
or
if guess == cars[1,2,3]
Reading the lists docs I saw that it's impossible to reference more than one index like, I tried above and of course that sends a syntax error.
The simplest way is:
if guess in cars:
...
but if your list was huge, that would be slow. You should then store your list of cars in a set:
cars_set = set(cars)
....
if guess in cars_set:
...
Checking whether something is present is a set is much quicker than checking whether it's in a list (but this only becomes an issue when you have many many items, and you're doing the check several times.)
(Edit: I'm assuming that the omission of cars[0] from the code in the question is an accident. If it isn't, then use cars[1:] instead of cars.)
Use guess in cars to test if guess is equal to an element in cars:
cars = ("red","yellow","blue")
guess = str(input())
if guess in cars:
print ("success!")
Use in:
if guess in cars:
print( 'success!' )
See also the possible operations on sequence type as documented in the official documentation.
#Sean Hobbs:
First you'd have to assign a value to the variable index.
index = 0
You might want to use while True to create the infinite loop, so your code would be like this:
while True:
champ = input("Guess a champion: ")
champ = str(champ)
found_champ = False
for i in listC:
if champ == i:
found_champ = True
if found_champ:
print("Correct")
else:
print("Incorrect")