I am taking in user input and creating objects with it. So I have a list of acceptable object names (A-E). What I figured I could do was pop(0) and use the return value as the name of the object. This way there is never a duplicate object name upon entry. Here is what I have so far I just cannot figure out how to assign the popped value to the name of the object properly.(Net is a defined class at the start of the program)
userIP = None
name_list = ['A', 'B', 'C', 'D', 'E']
while True:
if userIP == 'end':
break
userIP = input("Enter IP (type 'end' to exit): ")
userMask = input("Enter Mask: ")
name_list.pop(0) = Net(userIP, userMask)
print("The object just created would print here")
Put the results in a dictionary. Don't try to create variables with specified names. That way lies madness.
net_dict = {}
# ...
name = name_list.pop(0)
net_dict[name] = Net(userIP, userMask)
print(net_dict[name])
If you have them in a container, you may find you don't actually need the names. What are the names for, in other words? If the answer is just "to keep them in some order," use a list:
net_list = []
# ...
net_list.append(Net(userIP, userMask))
print(net_list[-1])
I just cannot figure out how to assign the popped value to the name of the object properly
It's not easy to do that, because it's not very useful to do that. What if you do get it to work, and you want to use the thing later on?
name_list.pop(0) = Net(userIP, userMask)
print ?.userMask
What do you put for the ? when you have no idea which variable name was used?
The right approach to this is #kindall's answer, or similar. But it is possible ( How can you dynamically create variables via a while loop? ) but not recommended.
Related
rookie here. Can anyone tell me what is wrong with this? I cant seem to print my "primer" string, I am sure that the "region" variable is not empty for I tested it out already.
enter image description here
In the future, please post the text of your program, not an image of the program.
I modified your program to do what I think your intent was.
The main thing you needed to do was call complement(region) and assign the return value to a variable.
dna = "ATCGATCGATCGTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAG"
print(f"#1 'dna' len={len(dna)} {dna}")
start = "3"
end = "30"
dna = dna[int(start):int(end)]
print(f"#2 'dna' len={len(dna)} {dna}")
region = dna[0:20]
print(f"#2 'region' len={len(region)} {region}")
def complement(region):
comp = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
primer = ''
for i in region:
primer = primer + comp[i]
return primer
com = complement(region)
print(f"'complement' len={len(com)} {com}")
Maybe the issue is the fact that you're trying to print the value outside the function, but the variable was defined inside of it, in a smaller scope
You are defining a function complement(), but you have not used this function.
Try assigning the result of your function to a new variable, something like that:
dna_compl = complement(region)
print(dna_compl)
VC_I=[1,2,4,3]
for i in range(len(VC_I)):
print(VC_i=[])
TypeError: 'VC_i' is an invalid keyword argument for this function
You need to use special module to get variable name. See here: Getting the name of a variable as a string
BTW, to make your example correctly iterating just the values do the following:
VC_I=[1,2,4,3]
for i in range(len(VC_I)): print(VC_I[i])
I don't know if you need this, but you can use the locals() to do this. For example, given your code:
VC_I=[1,2,4,3]
names_dict = dict(locals()) #Preserve a copy of all local variables
for key, val in names_dict.items():
if val == VC_I:
print('The variable name is:', key)
which will output, as you have guessed:
The variable name is: VC_I
However, this will only work if you are working with local variables. It also wouldn't work for variables with the exact same values. Take note.
edit
You can even do this:
for key, val in names_dict.items():
if val == VC_I:
print(key, ' = ', val)
which should give you:
VC_I = [1, 2, 3, 4]
Why dont you just use a dictionary for this purpose?
VC_I=[1,2,4,3]
x = {}
for i in range(len(VC_I)):
x[VC_I[i]] = [value, you, want]
To access use:
print(x["key name"])
To do what you wanted,
x = dict(zip(VC_I, PAYLOAD_IN))
I think you want to create list like VC_1, VC_2, ...
check this code
VC_I=[1,2,4,3,4,5,6,7,8]
PAYLOAD_IN=[ 'a2','123','21','1a','ae','23','12','ef']
for i in VC_I:
name = 'VC_'+str(i)
print(name) # here name variable is string
name = list()
print(name) # here name variable is list
print(type(name)) # checking data type of variable name
Answer for your specific question
for i, j in zip(VC_I, PAYLOAD_IN):
name = 'VC_' + str(i)
name = list()
name.append(j)
print(name)
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 am not sure how to word the question title.
a = "Alpha";
b = "Bravo";
c = "Charlie";
fn = input("What is your first name: ")
for fletter in fn.split():
fl = fletter[0]
The code above gets the first letter entered. The goal is to then get the first letter to possible check in a while loop to see if the value of fl = one of the starting strings. Is that possible to do? Tips on where to begin?
Solution 1 [Using a dictionary]
Also makes things much simpler.
In this case, instead of defining separate variables for each string, you store them in a dictionary. So for example, instead of this:
a = "Alpha"
b = "Bravo"
c = "Charlie"
You would have this:
letterwords = {"a":"Alpha", "b":"Bravo", "c":"Charlie"}
This works very similarly to a list, however instead of indexing the dictionary you would reference to separate objects inside a dictionary according to its key. So if the dictionary letterwords is defined as above, you would reference to the string Alpha by calling letterwords["a"]. Therefore, in this case, the code would look something like this:
letterwords = {"a":"Alpha", "b":"Bravo", "c":"Charlie"}
fn = input("Please enter your first name: ")
try:
letterwords[fn[0]]
except KeyError:
print("There is no matching variable with that letter in the database.")
Solution 2 [Using the eval() function]
Not recommended.
This is perfectly possible, with the eval function. However, you should be aware that this is a quite dangerous function to run, as malicious users can use this to control the console. (Especially if you imported os.) However, it should get you over the hump for now. Here's the code:
a = "Alpha"
b = "Bravo"
c = "Charlie"
fl = input("Please enter your first name: ")
try:
compared = eval(fl[0])
except NameError:
print("Your first name's first letter does not match any strings in the database.")
More information on the eval() function here: https://docs.python.org/3/library/functions.html#eval
Hope this helped!
I want to make a list and call it a name which I only know after I run the program:
For example:
#making shelfs
group_number = 1
group_name = 'group' + str(group_number)
print group_name
group_name will be: group1
Now I want to make an empty list called group1. How to do such a thing?
Usually you just put this into a dictionary:
d = {group_name:[]}
Now you have access to your list via the dictionary. e.g.:
d['group1'].append('Hello World!')
The alternative is to modify the result of the globals() function (which is a dictionary). This is definitely bad practice and should be avoided, but I include it here as it's always nice to know more about the tool you're working with:
globals()[group_name] = []
group1.append("Hello World!")
You are wanting to create a pseudo-namespace of variables starting with "group". Why not use a dict instead?
#making shelfs
groups = {}
group_number = 1
name = str(group_number)
groups[name] = [] # or whatever
print groups[name]
This is subtly different to #mgilson's answer because I am trying to encourage you to create new namespaces for each collection of related objects.
you do this:
locals()['my_variable_name'] = _whatever_you_wish_
or
globals()['my_variable_name'] = _whatever_you_wish_
or
vars()['my_variable_name'] = _whatever_you_wish_
Google to find out the differences yourself :P