How can i append an element to the list forever?It means if next time i open my file,the element i append still exist.Please help me thanks!
book_list=["good","best"]
new_book=input("Enter new book name")
book_list.append(new_book)
print(book_list)
Every time press one is triggered you init the book_list with empty list, and when user press two you also reinit the list overwriting the previous state. You should do this init before the loop that you have this conditions in.
You are basically creating new empty list ever time an action is triggered and you cannot do that if you want to see your updates.
By the init/clear i mean this line:
book_list = []
So it should look similar to this:
book_list = []
while True:
action = input("Chose 1 for... 2 for...")
if action == "1":
print(book_list)
elif action == "2":
new_book = input("Enter new book name")
book_list.append(new_book)
Related
I am self-studying "Python Crash Course" 2nd edition and I have come upon a problem that I am unable to solve. I have reread previous areas of the book, searched the internet and search other SO answers.
The official book answer uses a dictionary but I am trying to use a list.
The program should ask for input, add the input to a list and continue to repeat until told to stop. When told to stop, the entire list should be printed.
The problem that I am running into is that only the last item in the list in printing.
Instead of giving the answer, please just give me a hint so that I can truly learn.
Thanks,
chadrick
active = True
while active == True:
places = []
place = input("\nIf you could visit one place in the world, where would you go? ")
places.append(place)
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == 'no':
print(places)
active = False
The reason is because you're resetting the list back to empty for every iteration.
try the following:
active = True
places = []
while active == True:
place = input("\nIf you could visit one place in the world, where would you go? ")
places.append(place)
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == 'no':
print(places)
active = False
Also, since active is a boolean, you just need to do while active:
So:
active = True
places = []
while active:
place = input("\nIf you could visit one place in the world, where would you go? ")
places.append(place)
repeat = input("Would you like to let another person respond? (yes/no) ")
if repeat == 'no':
print(places)
active = False
I am trying to use
class reader
def __init__(self, name, booksread)
self.name = name
self.booksread = booksread
while True
option = input("Choose an option: ")
if option = 1:
#What to put here?
I want to create an unlimited number of instances of the reader class, But I could only figure out how to do it a limited number of times by using variables for the class. I also need to call the info later (without losing it). Is it possible to do this with a class? Or would I be better off with a list, or dictionary?
First: if option == 1: is always false in python 3, input only reads strings there.
Second: python lists can be expanded until you run out of RAM.
So the solution would be to create a list in the surrounding code and call append on that every time you have a new item:
mylist = []
while True:
mylist.append(1)
It's perfectly possibly to populate a data structure (such as a list or dict) with instances of a class, given your code example you could put the instances into a list:
class reader
def __init__(self, name, booksread)
self.name = name
self.booksread = booksread
list = []
while True:
option = input("Choose an option: ")
if option == 1:
list.append(reader(name,booksread))
Note: I don't know how you are obtaining the values for 'name' or 'booksread', so their values in the list.append() line are just placeholders
To access the instances in that list, you can then iterate over it, or access elements by their indexes, e.g.
# access each element of the list and print the name
for reader in list:
print(reader.name)
#print the name of the first element of the list
print(list[0].name)
I'm trying to scrape a career search website by going through all the different pages and I keep running into a problem when I try to append the dictionaries into a list using a for loop. When I execute the code below in Python 3.4, the code will pull all the relevant data from each page into a dictionary (I've checked with print()) and append into "FullJobDetails", but at the end of the for loop I get a list that is full of dictionaries from the last page only. The number of dictionaries is exactly the same as the number of pages in the list "ListofJobs". "ListofJobs" is a list of html links to each page that I am scrapping.
I just started learning code, so I know that the code below is not in any shape, way, or form the most efficient or best way of doing it. Any suggestions would be appreciated. Thanks in advance!
FullJobDetails = []
browser = webdriver.Chrome()
dictionary = {}
for jobs in ListofJobs:
browser.get(jobs)
dictionary["Web Page"] = jobs
try:
dictionary["Views"] = browser.find_element_by_class_name('job-viewed-item-count').text
except NoSuchElementException:
dictionary["Views"] = 0
try:
dictionary['Applicants'] = browser.find_element_by_class_name('job-applied-item-count').text
except NoSuchElementException:
dictionary["Applicants"] = 0
try:
dictionary["Last Application"] = browser.find_element_by_class_name('last-application-time-digit').text
except NoSuchElementException:
dictionary["Last Application"] = "N/A"
try:
dictionary["Job Title"] = browser.find_element_by_class_name('title').text
except NoSuchElementException:
dictionary["Job Title"] = "N/A"
try:
dictionary['Company'] = browser.find_element_by_xpath('/html/body/div[3]/article/section[2]/div/ul/li[4]/span/span').text
except NoSuchElementException:
dictionary['Company'] = "Not found"
try:
dictionary['Summary'] = browser.find_element_by_class_name('summary').text
except NoSuchElementException:
dictionary['Summary'] = "Not found"
FullJobDetails.append(dictionary)
The problem is that you create only a single dictionary - dicitonaries are mutable objects - the same ditionary is appended over and over to your list, and on each pass of the for loop you update its contents. Therefore, atthe end, you will have multple copies of the same dicitonry, all showing the information on the last page fectched.
Just create a new dictionary object for each run of the for loop. That new dictionary will be saved on the list, and the variable name dictionary can hold your new object with no conflicts.
for jobs in ListofJobs:
dictionary = {}
browser.get(jobs)
...
I am having accessing contents of a tuple. Every time I run the code I get the error message index out of range. I am trying to use a for loop to go through the tuple.
I have tried everything and failed.
The code is below:
# Check friend(s) selection
myTuple = chat_FriList.get(0,END)
tup = chat_FriList.curselection()
selected_friends = Listbox() # to hold selected friends for group chat
selected_friends.delete(0, END)
for item in tup:
user = myTuple[int(tup[item])]
selected_friends.insert(END, user)
if (len(tup) !=0):
print "Selected name:" + myTuple[int(tup[0])]
count=0
while count < len(friend_list):
msg = friend_list[count]
print selected_friends
if dpkg(msg)[3] in selected_friends: #dpkg(msg)[3] == myTuple[int(tup[0])]:
connect_client(myID, myPort, dpkg(msg)[1], int(dpkg(msg)[2]), 'C', EntryText)
count +=1
the full code is on this link. Basically im trying to create a group chat.
most of it working but i struggling to get a group chat going with selected users. anyhelp will be appreciated.
see full code:
client.py
server.py
More information is necessary to answer the question completely, but the following example from the REPL should be helpful. More debugging on your behalf is probably the best strategy.
a = ("a", "b", "c")
for item in a
print a[item]
a = (0, 1, 2)
for item in a
print a[item]
a = (10, 11, 21)
for item in a
print a[item]
I'm a new programmer and I'm having a difficult time finishing up my 4th program. The premise was to create a program that would take input from the user, creating a list then compares this list to a tuple. After it prints a statement letting the user know which items they chose correspond to the items in the tuple and also in which position they are in the tuple.
The problem I'm having is the last part, I can't get the correct position to print right and I fail to understand why. For example, if someone chose GPS correctly during their guesses, it should print position 0, but it doesn't. If water is chosen, it says it's in position 13...but it should be 5.
#here is the code I have so far:
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user
survival_gear = () #this is the tuple that will be compared against
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")
#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in case of a survival situation, think Bear Grylls. Once chosen, your list will be compared to the top 10 survival items list.")
while number_items_input < 10:
print("Please choose.")
guessed_items = input()
guessed_inventory_list.append(guessed_items)
number_items_input = number_items_input + 1
print ("You have chosen the following:", guessed_inventory_list)
#block of code below here compares the input to the tuple
t = 1
while t < 1:
t = t + 1
for individual_items in guessed_inventory_list:
for top_items in survival_gear:
if individual_items == top_items:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print ("You have chosen wisely", top_items)
print ("It's in position", t, "on the survival list")
t = t + 1
The reason you are getting a wrong index is because of the wrong nesting of loops , your outer loop should be the tuple you wish to compare and the inner loop should be the list generated from the input where as in this case it is reverse, see the below corrected code snippet
Code snippet:
for top_items in survival_gear:
for individual_items in guessed_inventory_list:
if individual_items == top_items:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print ("You have chosen wisely", top_items)
print ("It's in position", t, "on the survival list")
t = t + 1
The above code snippet should solve your problem , but your code contains
while loop which can be avoided using the range built in function
Incrementing the variable t manually can be avoided by using enumerate built in function
The nested forloop and if loop can be replaced by using the "in" membership test operator
Find the below updated code:
#!/usr/bin/python
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")
#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in caseof a survival situation, think Bear Grylls.Once chosen, your list will be compared to the top 10 survival items list.")
# One can use range functions to loop n times in this case 10 times
for i in range(0,10):
guessed_items = raw_input("Please choose:")
guessed_inventory_list.append(guessed_items)
print ("You have chosen the following:", guessed_inventory_list)
# Enumerate is one of the built-in Python functions.
# It returns an enumerate object.
# In this case that object is a list of tuples (immutable lists),
# each containing a pair of count/index and value.
# like [(1, 'GPS'), (2, 'map'), (3, 'compass'),...,(6, 'signal mirror')]
# in the below for loop the list of tuple will be
#unpacked in to t and individual_items for each iteration
for t,individual_items in enumerate(survival_gear,start=1):
#the "in" is a membership test operator which will test whether
#individual_items is in list guessed_inventory_list
if individual_items in guessed_inventory_list:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print("You have chosen wisely", individual_items)
print("It's in position", t, "on the survival list")