Specifically point to a list in a for loop - python

I have a class called Config with an object called "ip_list". There are two lists called ip_list1 and ip_list2. What I want to do is iterate though one of the ip lists based on a user selection. A simple version of my code is here:
ip_list1 = ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4']
ip_list2 = ['192.168.1.5', '192.168.1.6', '192.168.1.7', '192.168.1.8']
class Config:
def __init__(self):
self.ip_list = ""
list = int(input("Chose ip list: ")
if list == 1:
Config.ip_list = "ip_list1"
elif list == 2:
Config.ip_list = "ip_list2"
else:
print(f"{list} is an invalid choice")
for ip in Config.ip_list:
<do something>
This obviously doesn't work or I wouldn't be asking the question :)
It iterates through each letter of the actual string "ip_listx". How do I get it to point to the list and not just use the string?

You have a few issues with the code:
list is a data structure in python. Try renaming the variable from list to something else like foo.
You're using int() to handle taking an input but there's a syntax error because you forgot to include the trailing bracket for int().
It should be foo = int(input("Choose ip list: ")).
Sample:
ip_list1 = ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4']
ip_list2 = ['192.168.1.5', '192.168.1.6', '192.168.1.7', '192.168.1.8']
class Config:
def __init__(self):
self.ip_list = ""
foo = int(input("Chose ip list: "))
if foo == 1:
Config.ip_list = "ip_list1"
elif foo == 2:
Config.ip_list = "ip_list2"
else:
print(f"{foo} is an invalid choice")
for ip in Config.ip_list:
print(ip)
if __name__ == "__main__":
c = Config()

Related

How to write a function to print out a item in dictionary?

I am trying to define and call a function but I am stuck on what to put all I know currently is that I definitely need a for loop .
I want my output to be 867-5309
from an input of
Input 1: Joe 123-5432 Linda 983-4123 Frank 867-5309
Input 2: Frank
Though obviously I need it to work for any input that is placed into the name input
def get_phone_number(my_dict, contact_name):
phone_number = ''
return phone_number
if __name__ == '__main__':
word_pairs = input()
my_list = word_pairs.split()
name = input()
my_dict = {}
for i in range(0, len(my_list), 2):
my_dict[my_list[i]] = my_list[i + 1]
print(get_phone_number(dict, name))
I already know my dictionary works fine my only problem is with formatting a function that will give me the output I want, I am struggling with functions and just need a little help to get the result I want.
You don't need a function for this. And least of all a loop. You can just call the entry of my_dict using the key:
if __name__ == '__main__':
word_pairs = input("Enter Words: ")
my_list = word_pairs.split()
name = input("Enter Name: ")
my_dict = {}
for i in range(0, len(my_list), 2):
my_dict[my_list[i]] = my_list[i + 1]
print(my_dict[name])

First input not inserting into List

I am writing a program to accept user input to build a sentence word-by-word. After the user is done it is supposed to display the the sentence and the amount of words in the list. I know my code isn't complete and I am only requesting help for one issue. As of the moment I cannot get the first input to append or insert into the list, while others are. Any help would be great. I have been searching for awhile with no progress.
Code:
index = 0
def main():
wordList = []
inputFunc(wordList = [])
def inputFunc(wordList = []):
global index
print("To make a sentence, enter one word at a time... ")
wordInput = input("Enter word... : ")
wordList.insert(index,wordInput)
index += 1
choice = input("(y = Yes, n = No, r = Reset List)Another word?: " )
inputCalc(choice)
completeList(wordList)
def inputCalc(choice):
while choice == 'y':
inputFunc()
while choice == 'n':
return
while choice == 'r':
clearList()
def completeList(wordList):
print(wordList)
exit()
def clearList():
wordList.clear()
main()
main()
There's lots of issues with your code, but the main reason why your word is not being appended to your list is because mutable default arguments don't generally do what you want.
Instead just perform everything in a single function.
def main():
inputFunc()
def inputFunc():
running = True
wordList = []
while running:
print("To make a sentence, enter one word at a time... ")
wordInput = input("Enter word... : ")
wordList.append(wordInput)
while True:
choice = input("(y = Yes, n = No, r = Reset List)Another word?: " )
if choice == 'y':
break
elif choice == 'n':
running = False
break
elif choice == 'r':
wordList = []
break
print(wordList)
if __name__ == "__main__":
main()
The detailed answer is The first time you call inputFunc() inside main() you pass an empty list:
def main():
wordList = []
inputFunc(wordList=[])
When you call it again via recursion inside inputCalc(choice) you call inputFunc() without passing any arguments thus using a different list, the pre-initialized list.
def inputCalc(choice):
while choice == 'y':
inputFunc()

creating new classes in a loop according to user input

So I'm trying to make a prime sieve that will make a class object that stores the prime number up to a number the user gives. But I want to run in a loop where the user can keep creating new objects with lists of prime numbers stored, and give them the option to keep doing that.
If they input the same number twice, I want to just print the previous results which have been stored inside the object created from before, instead of replacing the previous object and running through the computing of setting up a whole new list.
I think the only thing I'm hung up on is how do I just keep creating new class objects over and over and give the objects new names every time instead of what I did the first time, storing the object in the variable 'c'.
If you look at my code, the sieve will work properly, I just don't know how to make an object without storing it in the variable 'c'
history={}
class Eratosthenes(object):
def __init__(self,b):
self.limitn=int(b)+1
self.not_prime = [False]*self.limitn
self.primes = []
def do_primes_sieve(self):
for i in range(2, self.limitn):
if self.not_prime[i]:
continue
for f in xrange(i**2, self.limitn, i):
self.not_prime[f] = True
self.primes.append(i)
def get_primes_til(self):
for i in self.primes:
print (i)
def get_num_of_primes(self):
print (len(self.primes))
a = True
while a:
b = raw_input("How far are you going to search?: ")
if b in history.keys():
c = history[b]
c.get_num_of_primes
else:
c = Eratosthenes(b)
history[b] = c
c.do_primes_sieve()
c.get_primes_til()
d = raw_input("Continue? (type 'yes' or 'no'): ")
if d == "yes":
continue
elif d == "no":
a=False
else:
print "This is a 'yes' or 'no' question. We're done here."
a=False
You could declare some class variable (aka static variable), e.g. a dictionary called history, which will store results:
class Eratosthenes(object):
history = {}
def __init__(self,b):
self.limitn=int(b)+1
self.not_prime = [False]*self.limitn
self.primes = []
def do_primes_sieve(self):
if self.limitn-1 in Eratosthenes.history.keys():
self.primes = Eratosthenes.history[self.limitn-1]
else:
for i in range(2, self.limitn):
if self.not_prime[i]:
continue
for f in xrange(i**2, self.limitn, i):
self.not_prime[f] = True
self.primes.append(i)
Eratosthenes.history[self.limitn-1] = self.primes
Then, you could modify your do_primes_sieve method so that, if a previous answer exists in the history dictionary, the primes for the current instance of Eratosthenes will be fetched from the dictionary.
Per discussion below, an updated answer that treats history as a global:
history = {}
class Eratosthenes(object):
def __init__(self,b):
self.limitn=int(b)+1
self.not_prime = [False]*self.limitn
self.primes = []
def do_primes_sieve(self):
for i in range(2, self.limitn):
if self.not_prime[i]:
continue
for f in range(i**2, self.limitn, i):
self.not_prime[f] = True
self.primes.append(i)
def get_primes_til(self):
for i in self.primes:
print i
def get_num_of_primes(self):
print len(self.primes)
a = True
while a:
b = raw_input("How far are you going to search?: ")
if b in history.keys():
c = history[b]
c.get_num_of_primes()
else:
c = Eratosthenes(b)
history[b] = c
c.do_primes_sieve()
c.get_primes_til()
d = raw_input("Continue? (type 'yes' or 'no'): ")
if d == "yes":
continue
elif d == "no":
a=False
else:
print "This is a 'yes' or 'no' question. We're done here."
a=False

adding accessing and deleting items from a python list

Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is empty constantly as well as other errors under other functions in the code.
def display_menu():
print("")
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("9. Exit ")
print("")
return int(input("Selection> "))
def printmembers():
if namelist > 0:
print(namelist)
else:
print("List is empty")
def append(name):
pass
def addmember():
name = input("Type in a name to add: ")
append(name)
def remove():
pass
def removemember():
m = input("Enter Member name to delete:")
if m in namelist:
remove(m)
else:
print(m, "was not found")
def index():
pass
def editmember():
old_name = input("What would you like to change?")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name? ")
namelist[item_number] = new_name
else:
print(old_name, 'was not found')
print("Welcome to the Team Manager")
namelist = 0
menu_item = display_menu()
while menu_item != 9:
if menu_item == 1:
printmembers()
elif menu_item == 2:
addmember()
elif menu_item == 3:
removemember()
elif menu_item == 4:
editmember()
menu_item = display_menu()
print("Exiting Program...")
For starting out, you've got the right ideas and you're making good progress. The main problem is how you defined namelist = 0, making it a number. Instead, namelist needs to be an actual list for you to add or append anything to it. Also, you're append() method is not necessary since once you define namelist as a list, you can use the built-in list.append() method, without having to write your own method.
So here are a few suggestions/corrections, which once you have the basis working correctly, you should be able to work out the rest of the bug fixes and logic.
Since you don't have any main() method, you can define namelist on
the first line of code, before any other code, so that it is
referenced in each method:
namelist = [] # an empty list
Change addmember() method to:
def addmember():
name = raw_input("Type in a name to add: ")
namelist.append(name)
Since namelist is a list, we can use the built-in len() method on nameslist to check if it's empty when printing out its contents (if any):
def printmembers():
if len(namelist) > 0: # Get the length of the list
print(namelist)
else:
print("List is empty")
Now that the Add() menu option is working for adding a name to the namelist, you should be able to implement removing, and editing names to the list using similar logic.
You should consider initializing the list to be empty instead of zero (unless you want that element).
namelist = list()
Also, your append method does not perform any actions. It's also pretty unnecessary since you can just use the append method of list.
def addmember():
name = input("Type in a name to add: ")
namelist.append(name)
If you did want to make your own append method you should understand that the variables in the function definition are inputs, so just saying def append(name) won't perform any action. In this case name is the identifier you are applying to the input argument. You could just as easily call it anything you wanted. A good way to understand this is by assigning the argument a different variable name than the one you pass it. Like this:
def append(nameToAppend):
namelist.append(nameToAppend)
You can call your append method in addmember like this:
def addmember():
name = input("Type in a name to add: ")
append(name)
After getting name from input, you call the append(name) method, yet your append method doesn't do anything yet.
In your append method you have to add the name you get to your namelist, like how you do in the editmember method.

Python- Key from dict on user input eval. Send to overloaded operator function

For starters here is my current code:
import ipaddress
class Net():
def __init__(self, ip, mask):
self.ip = ip
self.mask = mask
def getipmask(self):
return self.ip, self.mask
def __mul__(self, ip1, ip2, sn1):
ip1_Bin = [bin(int(ip1))[2:].rjust(8,'0') for ip1 in ip1.split('.')]
IP1 = ''.join(ip1_Bin)
ip2_Bin = [bin(int(ip2))[2:].rjust(8,'0') for ip2 in ip2.split('.')]
IP2 = ''.join(ip2_Bin)
sn_Bin = [bin(int(sn1))[2:].rjust(8,'0') for sn1 in sn1.split('.')]
SUB1 = ''.join(sn_Bin)
IP1Final = (IP1 + "/" + SUB1)
IP2Final = (IP2 + "/" + SUB1)
if ipaddress.ip_address(IP1Final) in ipaddress.ip_network(IP2Final, strict=False):
print("")
print("Same Subnet!")
else:
print("")
print("Different Subnet!")
userIP = None
name_list = ['A', 'B', 'C', 'D', 'E']
net_dict = {}
while True:
userIP = input("Enter IP (type 'end' to exit): ")
if userIP == 'end':
break
userMask = input("Enter Mask: ")
name = name_list.pop(0)
net_dict[name] = Net(userIP, userMask)
#print out all ip/mask combos with proper names
print('')
for x in net_dict:
print(x, "-->", net_dict[x].getipmask())
print('')
#evaluations
while True:
userFuncIn = input("Please enter a function (e.g. A+B). Enter 'end ' to stop: ")
charList = list(userFuncIn)
#Get the object letters
charList_Objs = charList[0:][::2]
#Get the operators
charList_Ops = charList[1:][::2]
#assign letter value to proper ip and subnet values
for x in charList_Objs:
x = net_dict[x].getipmask()
#Get number of operators
numberofOps = len(charList_Ops)
#while charList_Ops still has operations
while len(charList_Ops) != 0:
#current operator
operator = charList_Ops.pop(0)
#xpression with proporly assigned values on objects
expression = [charList_Objs[0], operator, charList_Objs[1]]
#convert from list to string to use in eval
exp_str = "".join(expression)
#Delete objects 0 and 1 from the charList
del(charList_Objs[0:1])
print(eval(exp_str))
What should be happening is after all the user's inputs are displayed with their corresponding letter they are able to enter what function they want to preform. For now to keep it simple I am just focusing on __mul__. What __mul__ will do is take in two IP/subnet combos and evaluate them to see if they are on the same subnet. I can fix the code in the __mul__ function once I properly figure out how I am to get the user's function entry to work properly. So if user enters A*B. It should take A and B from net_dict and then send those 2 key/value pairs to the overridden __mul__ function to perform. The correct action.
Any help or suggestions would be much appreciated.
PS: Other functions (not __mul__) will allow for multiple operations and multiple IP/subnet pairs. For example (A+B+C) so that is why I added charList_Ops and charlist_Objs. If it was just a case where there was always 3 chars in the user entered function (e.g. A*B) that would obviously not be needed.
This is tricky. The naive way to do this is of course just eval, but that's ugly. Instead let's do this:
import re
import operator
operators = {"*": operator.mul,
"+": operator.add,
"-": operator.sub,
"/": operator.truediv} # add or delete from this dict as desired
re_splitters = re.compile('|'.join([re.escape(splitter) for splitter in operators.keys()])
user_input = input("Here's a prompt! ")
Alice, Bob = map(net_dict.get, re_splitters.split(user_input))
# this may give you errors if you have a poorly formed user input. Catch and handle
# those errors as appropriate
action = re_splitters.search(user_input).group(0)
result = operators[action](Alice, Bob)
You could also do:
Alice, Bob = re_splitters.split(user_input)
# YOU MUST CHECK HERE THAT ALICE AND BOB ARE BOTH IN net_dict
action = re_splitters.search(user_input).group(0)
if action:
result = eval("net_dict[{}] {} net_dict[{}]".format(Alice, action, Bob))
# strong warning about an injection vulnerability!
But imagine the case where you fail to check if Alice and Bob are in net_dict and a malicious user does:
>> # User input below:
known_key];import os;os.system("format C:");net_dict[known_key+known_key
Which then becomes:
net_dict[known_key]
import os
os.system("format C:")
net_dict[known_key] + net_dict[known_key]
Congratulations, the hard drive is now toast.

Categories

Resources