#homework basic python
99 messages · Page 1 of 1 (latest)
Nothing really
I have a class with the dunder init and str
I have opened the file using with as
Easier than explaining it lol
I dont have discord on my laptop
Could I send a picture
The code is not very long
You just said you have nothing lol
You can readlines below row 0,
then use split() on each line to make out of 1 string a kist of strings (based on seperator)
append this list on another list (so you have a list of lists)
You need to create a class for your country objects (best to also have a class attribute for appending each new created object and one class method to get a list of these objects)
Then it just matters how you builded up your class and you can take the list_list with a for loop and go through it.
Then do smth like:
CountryClass(element[0], element[1]...)
and so on for the list elements per line.
There you have your clas with a object list you can call đ
(you csn also create the objects while reading in lines, so you dont need to create a list first)
Hey @limber plover, Could you please share some of the code youâve written so far? It would help the community better understand where youâre encountering issues, and we can provide more specific guidance.
Literally what I was saying lol
I am reminding him that we are here for him
đ
Thanks a lot
Youâre too kind
Sorry for being afk
I was in a call and had my hands full
But I think Iâve made some headway in the code
class Land():
def __init__(self, namn, folkmÀngd, landlÄst):
self.namn = namn
self.folkmÀngd = folkmÀngd
self.landlÄst = landlÄst
#def __repr__(self):
#return f" Namn: {self.namn}"
lista_lÀnder = []
with open("europa.txt") as infil:
infil.readline()
for line in infil:
lista = []
for word in line.split(","):
if word:
lista.append(word.strip())
land = Land(namn=lista[0], folkmÀngd=lista[2], landlÄst=lista[3])
lista_lÀnder.append(land)
for land in lista_lÀnder:
print(land.namn)
this is my code rn
so I had an issue with converting a file into lines which creates an object of each file
Use discord format....
infil.readline() might not be the best way to do it. It reads one line at a time which means you will need to call it multiple times and know when to stop calling it
Instead, you can directly loop over infil to get each line, or loop over infil.readlines(), or infil.read().split("\n")
I did that to get rid of the line header
Convert the 'folkmÀngd' value to an integer when you create the 'Land' object. This is how you can update the code:
land = Land(namn=lista[0], folkmÀngd=int(lista[2]), landlÄst=lista[3])
This way, the population is stored as an integer, allowing you to use it for numerical operations, such as sorting countries by population or performing calculations. Just make sure the file data is correctly formatted (i.e., no missing values) to avoid errors during conversion.
Could you use code blocks? It's hard to read your code
def __init__(self, namn, folkmÀngd, landlÄst):
self.namn = namn
self.folkmÀngd = folkmÀngd
self.landlÄst = landlÄst
#def __repr__(self):
#return f" Namn: {self.namn}"
lista_lÀnder = []
with open("europa.txt") as infil:
infil.readline()
for line in infil:
lista = []
for word in line.split(","):
if word:
lista.append(word.strip())
land = Land(namn=lista[0], folkmÀngd=lista[2], landlÄst=lista[3])
lista_lÀnder.append(land)
for land in lista_lÀnder:
print(land.namn)```
Doesnt this just create a land object with the name
This is what I did, no?
Oh
Yea I could do that
Iâm kinda stuck on something else rn
When I append the âlandâ objects to the list
It creates a whole list of objects
Should I append the land objects one at a time to a list in a loop then append that to a new list?
So I get each object as a list in a big list
class Country():
_country_list = []
def __init__(self, name: str, area: int, num_residents: int, landbound: bool)
self.name = name
self.area = area
self.num_residents = num_residents
self.landbound = landbound
Country._country_list.append(self)
@classmethod
def get_all(cls):
return cls._country_list
def readout_doc(doc_path, has_title_line: bool = True, seperator: str = ","):
with open(doc_path, "r") as doc:
for line in doc:
if has_title_line:
has_title_line = False
continue
name, area, num, bound = (line.strip()).split(seperator)
Country(name, area, num, bound)
def start():
readout_doc("my_textfile.txt")
country_list = Country.get_all()
for co in country_list:
print(co)
if __name__ == "__main__":
start()
This is basically what your goal should be (if i understood you correct)
(NOT TESTED! Just wrote that on top of my head, so minor errors you need to solve yourself :D)
No u haven't.. I am sorry for not replying earlier....
There's no need to create a list of lists. You're already on the right track with appending each 'Land' object to a single list as you loop through the file. When you append each 'Land' object to 'lista_lĂ€nder' one at a time, youâre building a list where each element is a 'Land' object, which is exactly what you want. This way, you can easily access each object later by iterating over 'lista_lĂ€nder' directly. If you created a list of lists, it would make accessing and managing the objects more complicated. So, just keep appending the 'Land' objects directly to the list within your loop, and you should be good to go
The code ended up being shitty as hell
But it works
Just got done
lista = [] #
class Land():
def __init__(self, namn, folkmÀngd, landlÄst):
self.namn = namn
self.folkmÀngd = folkmÀngd
self.landlÄst = landlÄst
def __str__(self):
return f" {self.namn}, {self.folkmÀngd}"
def __repr__(self):
return f" {self.namn}, {self.folkmÀngd}"
def fil_till_lista(fil):
lista_lÀnder = []
with open(fil, "r", encoding = "utf-8") as fil:
fil.readline() # ta bort rad 1
for line in fil: # line gÄr över alla rader 1 och 1
skapar 1 tom lista
for word in line.split(","): # för ord i rad som gjorts till lista
word = word.strip()
if word: # om ordet inte Àr tomt
lista.append(word) # lÀgg till ordet i lista
lista_lÀnder.append(lista)
return lista_lÀnder
def landlÄsta_lÀnder(fil):
ny_lista = []
for lista in fil:
namn = lista[0]
folkmÀngd = int(lista[2])
landlÄst = lista[3]
land = Land(namn, folkmÀngd, landlÄst)
if landlÄst == "Y":
ny_lista.append(land)
return ny_lista
def rÀkna_ut_invÄnare(lista):
total = 0
for i in lista:
total += i.folkmÀngd
return total
def main():
fil = input("VĂ€lj en fil:")
call = fil_till_lista(fil)
call2 = landlÄsta_lÀnder(call)
print("I Europa har följande lÀnder inte tillgÄng till hav:")
for i in call2:
print(i.namn)
invÄnare = rÀkna_ut_invÄnare(call2)
print(f"Totalt bor i dessa 14 lÀnder: {invÄnare} mÀnniskor")
main()
Swedish variable names give me anxiety but if it works it works đŁïž
defo scandinavian and doesn't look Danish or Norwegian 
I didn't know you could use funny characters in Python variable names, learned something new today damn
Thought that was a Swift thing
Yet you taught me a new thing about Python
What do you need help with exactly?
The code looks horrible
Sure it gets the job done
But do you see any ways of making it shorter
Any thing youâd change (without it being everything)
will check in a bit but I'd probably add type hints
def __init__(self, namn, folkmÀngd, landlÄst):
self.namn = namn
self.folkmÀngd = folkmÀngd
self.landlÄst = landlÄst
def __str__(self):
return f"{self.namn}, {self.folkmÀngd}"
def fil_till_lista(fil):
with open(fil, "r", encoding="utf-8") as f:
f.readline() # Remove header
return [line.strip().split(",") for line in f if line.strip()]
def landlÄsta_lÀnder(data):
return [Land(namn, int(folkmÀngd), landlÄst) for namn, _, folkmÀngd, landlÄst in data if landlÄst == "Y"]
def rÀkna_ut_invÄnare(lÀnder):
return sum(land.folkmÀngd for land in lÀnder)
def main():
fil = input("VĂ€lj en fil: ")
data = fil_till_lista(fil)
landlÄsta = landlÄsta_lÀnder(data)
print("I Europa har följande lÀnder inte tillgÄng till hav:")
for land in landlÄsta:
print(land.namn)
print(f"Totalt bor i dessa {len(landlÄsta)} lÀnder: {rÀkna_ut_invÄnare(landlÄsta)} mÀnniskor")
main() ```
I hope it helps
Beginner friendly pls
type hints are good
The return in the first function, does the [ ] create a list of is it used in all list comprehensions?
@hybrid pine
Yes
Yes, the square brackets in a list comprehension create a new list.
And this is even worse
could it be that you totaly oversaw my script? xD
Basically that should include all you need to do.
Just need to rewrite it in your style & test
"read a text file into a program and make objects of each country"
as simple as possible pretty simple solved (except that i added the list as class attribute, so you dont have to work with globalizing vars in your script.
class Land:
def __init__(self, name, folkmangd, landlast):
self.name = name
self.folkmangd = folkmangd
self.landlast = landlast
def __repr__(self):
return f"Land: {self.name}, {self.folkmangd}, {self.landlast}"
lista_lander = [Land(*[x.strip() for x in line.split(',')]) for line in open('europa.txt')]
print(*lista_lander, sep='\n')
this wont work, because first line has headers/title
also its just taking 3 attributes, but each line has 4 elements xD
How about we stop trying to just give answers and instead try teach them how to get to the answer themselves :))
Then we should teach programming, not python code now đ
- What should be the final output?
- How should it be saved/build up before?
- What do you need for that?
- Where do you get the data from?
- How do you get the data?
- What do you need to look after, when reading in the data?
Just following this questions one by one will result in that script above xD
i didn't even know what he wanted i just read the code he wrote and shortened it