Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having a peculiar problem with values inside an object being set to whatever I set that variable to in later new instances. Let me try to explain first with an example of the kind of results I'm getting given doc.python.org's example on how to use class objects.
b = Dog("Buddy")
e = Dog("Spot")
b.Name
e.Name
for me gives an output of
Spot
Spot
With the help of some debug lines, I've found that this phenomenon occurs when coming out of for loop. So here is my actual code and it's results:
tempTray = Tray("{0}:{1}".format(UnitName, TrayName))
for eachDish in range(len(tempTray.GridSizes)):
if Row1.find("[") > -1:
Parse = Row1[Row1.find("[")+1:Row1.find("]")]
Row1 = Row1[Row1.find("]")+1:]
elif Row2.find("[") > -1:
Parse = Row2[Row2.find("[")+1:Row2.find("]")]
Row2 = Row2[Row2.find("]")+1:]
elif Row3.find("[") > -1:
Parse = Row3[Row3.find("[")+1:Row3.find("]")]
Row3 = Row3[Row3.find("]")+1:]
if Parse != "Empty":
tempTray.GridSizes[eachDish] = Parse[:Parse.find(" ")]
tempTray.GridColors[eachDish] = self.Colors[Parse[Parse.find(" ")+1:]]
# Check point 1
self.AllTrays.append(tempTray)
# Check point 2
At # Check point 1 I have a debug print test that writes the contents of tempTray's 2 values, and the contain the correct information at this point, but if I check the same thing again at # Check point 2, now they become set to whatever is in the last tray loaded by the xml file (and I've tried looking at all 4 trays, not just self.AllTrays[0], they all have the same values) I've also ruled out that my xml file is saved with changes current.
Any solutions or workarounds? I've come across this before but without consistency (a card game where the card data loaded from a file correctly but each player was being set to the name "Player 2" and their score values both went up and down if I changed either one of their scores)
It'd be good to see the actual code for your Dog class's definition. Chances are you have made Name a class variable as opposed to an instance variable (the Python documentation actually uses a Dog class to show the difference).
The Python documentation actually has a great short and sweet explanation of Class and Instance Variables; so, I suggest you read it and ask more questions if need be.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
i'm new here, just started to learn Python 2 days ago, i just made my first program, half done, i need help with the rest please i've tried evrything i could but i'm struggling.
the program is about web scraping a currency (name and value) then use the data to select a specific currency, display it + value then enter a specific Alert_value, if the Alert_value is reached then i get notification.
i could scrape the data using BS4 but i couldn't use it as individual data Currency + it's value, no idea if i have to use it as list or other but i have tried list but my 2 days of experience didn't help :D
the whole Currency data is index[0] i think the problem is that i couldn't make a list out of the Currency name data, index[1] is out of range means that 150 currency name is at index[0].
Annyone can help me please how to put the data of both Currency names and value, and how to select each one individually to display it, please use simple words when explaining i'm just starting. Thank you.
Some of the Code : name is currency name and price is the currency price
for container in containers:
name_container = container.findAll("a", {"class":"tv-screener__symbol"})
name = name_container[0].text
title_container = container.findAll("td", {"class":"tv-data-table__cell tv-screener-table__cell tv-screener-table__cell--big"})
price = title_container[2].text
# print(str(name) + " : " + price)
Xt=[name,price]
print(Xt)
Hi & welcome #HannibalB!
I am a new contributor myself, so unfortunately I cannot comment yet. As far as I understand correctly, you would like to query a currency name - e.g. Nexo - and have the respective value displayed.
Python offers many different data types, all of which are useful for different purposes. In your case, I would suggest a dictionary. Check out the link, if you would like to know more.
What you could do, is adjust the code slightly (I am assuming here that it already works as intended):
Dictionary = {}
for container in containers:
name_container = container.findAll("a", {"class":"tv-screener__symbol"})
name = name_container[0].text
title_container = container.findAll("td", {"class":"tv-data-table__cell tv-screener-table__cell tv-screener-table__cell--big"})
price = title_container[2].text
# print(str(name) + " : " + price)
Dictionary[name] = price
You can now simply access the elements in the dictionary like so:
Dictionary['Nexo']
This will then display the price/value that is stored under the so called dictionary key, which in this case is Nexo. In case you prefer pandas.DataFrame, you can easily convert a dictionary into one. Check out the link.
You might have also thought about appending a DataFrame directly. Even though I am not an expert, I would advise against that. A DataFrame is quite a heavy data structure and it is usually more efficient to convert you data into a DataFrame as a final step.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So I am trying to get into python, and am using other examples that I find online to understand certain functions better.
I found a post online that shared a way to check prices on an item through CamelCamelCamel.
They had it set to request from a specific url, so I decided to change it to userinput instead.
How can I just simply loop this function?
It runs fine afaik once, but after the inital process i get 'Process finished with exit code 0', which isn't necessarily a problem.
For the script to perform how I would like it to. It would be nice if there was a break from maybe, 'quit' or something, but after it processes the URL that was given, I would like it to request for a new URL.
Im sure theres a way to check for a specific url, IE this should only work for Camelcamelcamel, so to limit to only that domain.
Im more familiar with Batch, and have kinda gotten away with using batch to run my python files to circumvent what I dont understand.
Personally if I could . . .
I would just mark the funct as 'top:'
and put goto top at the bottom of the script.
from bs4 import BeautifulSoup
import requests
print("Enter CamelCamelCamel Link: ")
plink = input("")
headers = {'User-Agent': 'Mozilla/5.0'}
r = requests.get(plink,headers=headers)
data = r.text
soup = BeautifulSoup(data,'html.parser')
table_data = soup.select('table.product_pane tbody tr td')
hprice = table_data[1].string
hdate = table_data[2].string
lprice = table_data[7].string
ldate = table_data[8].string
print ('High price-',hprice)
print ("[H-Date]", hdate)
print ('---------------')
print ('Low price-',lprice)
print ("[L-Date]", ldate)
Also how could I find the difference from the date I obtain from either hdate or ldate, from today/now. How the dates I parsed they're strings and I got. TypeError: unsupported operand type(s) for +=: 'int' and 'str'.
This is really just for learning, any example works, It doesnt have to be that site in specific.
In Python, you have access to several different types of looping control structures, including:
while statements
while (condition) # Will execute until condition is no longer True (or until break is called)
<statements to execute while looping>
for statements
for i in range(10) # Will execute 10 times (or until break is called)
<statements to execute while looping>
Each one has its strengths and weaknesses, and the documentation at Python.org is very thorough but easy to assimilate.
https://docs.python.org/3/tutorial/controlflow.html
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I’m teaching myself programming, using Python as my initial weapon of choice.
I have learnt a few basics and decided to set myself the challenge of asking the user for a list of names, adding the names to a list and then finally writing the names to a .csv file.
Below is my code. It works.
My question is what would you do differently, i.e. how could this code be improved for readability and efficiency. Would you approach the situation differently, structure it differently, call different functions? I am interested in, and would appreciate a great deal, the feedback from more experienced programmers.
In particular, I find certain parts clunky; such as having to specify to the user the required format for data entry. If I were to simply request the data (name age location) without the commas however, then each record, when written to .csv, would simply end up as one record per cell (Excel) – this is not the desired result.
#Requesting user input.
guestNames = input("Please enter the names of your guests, one at a time.\n"\
"Once you have finished entering the information, please type the word \"Done\".\n"\
"Please enter your names in the following format (Name, Age, Location). ").capitalize()
guestList.append(guestNames)
while guestNames.lower() != "done".lower() :
guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()
guestList.append(guestNames)
number += 1
#Sorting the list.
guestList.sort()
guestList.remove("Done")
#Creating .csv file.
guestFile = open("guestList.csv","w")
guestFile.close()
#Writing to file.
for entries in guestList :
guestFile = open("guestList.csv","a")
guestFile.write(entries)
guestFile.write("\n")
guestFile.close()
I try to write down your demands:
Parse the input string according to its structure (whatever) and save results into a list
Format the result into CSV-format string
write the string to a CSV file
First of all, I would highly recommend you to read the a Python string operation and formatting tutorial like Google Developer Tutorial. When you understand the basic operation, have a look at official documentation to see available string processing methods in Python.
Your logic to write the code is right, but there are two meaningless lines:
while guestNames.lower() != "done".lower()
It's not necessary to lower "done" since it is already lower-case.
for entries in guestList :
guestFile = open("guestList.csv","a")
Here you open and close the questList.csv every loop, which is useless and costly. You could open the file at the beginning, then save all lines with a for loop, and close it at the end.
This is a sample using the same logic and different input format:
print('some notification at the beginning')
while true:
guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()
if guestNames == 'Done':
# Jump out of the loop if user says done
break
else:
# Assume user input 'name age location', replace all space with commas
guestList.append(guestNames.replace(' ', ','))
number += 1
guestList.sort()
# the with keyword will close the guestFile at the end
with open("guestList.csv","w") as guestFile:
guestFile.write('your headers\n')
for entries in guestList:
guestFile.write('%s\n' % entries)
Be aware that there are many ways to fulfil your demands, with different logics and methodologies.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to store some kind of persistent tracking to my application. Like for example ,
application.py supports 3 arguments, --firstarg --secondarg --thirdarg.
user can execute application.py using either one of the argument. I want to provide a feature where in user can track that he has already completed running the firstarg. In order to achieve this, i wanted to store a file called status.log, where the tracker will be stored.
Initially, status.log has
firstarg : 0
secondarg : 0
thirdarg : 0
once the user executes the first arg, it should turn the line , firstarg : 1
so when users wants, he can check if he has already completed running the firstarg or not.
Is it possible ?
I tried shelve, its not working for me for some reason. I am not seeing any logs written to the file.
Thanks.
I'd say use a JSON file as a persistent store and use the load and dump methods for reads and writes.
The JSON method is built in so all you need is to import it and use it:
import json
data_file = '/path/to/file'
# Load current state from file
contents = json.load(data_file)
# Do something
# ....
# ....
# Change values
contents['firstarg'] = firstarg
# Save to file
json.dump(contents, data_file)
Since you don't have a code sample, this is a simple approach
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to find a way to do both actions:
1) Retrieving a gender from a name
2) Retrieving a gender from a username (similar to the previous one but different)
I reviewed some methods how to do 1) (including: Does anyone know of a good library for mapping a person's name to his or her gender?), and might do it, but I have a problem to do the second:
Let's say that I have a dictionary containing all names split to female or male. Now I want to take a username and try to see whether the username contains one of these names (because username can contain more than just the first name itself) - what's the best way to do it? It seems not efficient to go over all the dict keys and look for them in the username one by one... There must be an optimized method...
Hope that I explained myself clearly, any help would be very much appreciated!!
A dictionary will only help in the case that the user name (or name) is an exact match. It may be best to use a simple list:
Make certain that the names you include in girl_names and boy_names are fully gender-specific. (For instance, Ben wouldn't work, since both men and women could go by Ben.) Also make sure that the lists don't have any repeated partial names, E.g. "Al" and "Albert".
girl_names = Large set of likely female-only names, all lower-case.
boy_names = Large set of likely male-only names, all lower-case.
user_name = The user name you're looking up.
def name_gender(user_name, boy_names=None, girl_names=None):
uname = user_name.lower()
girliness = 0
for girl_name in girl_names:
if girl_name in uname:
girliness += 1
boyishness = 0
for boy_name in boy_names:
if boy_name in uname:
boyishness += 1
if boyishness > girlishness: return 'Male'
if girlishness > boyishness: return 'Female'
return 'Androgynous'
This function is only a loose proxy for real intended user name gender. Lists of common names are available from various web sites, and can also be obtained from the Census information.