Below is my code. It is giving me a compile error saying that artist has not been defined. This confuses me since artist is a parameter I'm passing.
Thanks.
class Track:
def __init__(self, artist, title, album=None):
self.artist = str(artist)
self.title = str(title)
self.album = album
def __str__(self):
return self.artist + " " + self.title + " " + self.album
def set_album(self, album):
self.album = album
class Album:
def init(self, artist, title, year='', genre='', tracks=None):
self.artist = str(artist)
self.title = str(title)
self.year = str(year)
self.genre = str(genre)
self.tracks = tracks
def __str__(self):
return self.artist + " " + self.title + " " + self.year + " " + self.genre + " " + self.tracks
def add_track(track):
self.tracks.append(track)
def music_library(tracks, albums):
while true:
command = raw_input("Please enter a command (s, st or sa)").lower()
if "s " in command:
searchText = command.split()(1)
elif "sa " in command:
searchText = command.split()(1)
elif "st " in command:
searchText = command.split()(1)
import os
from mutagen.mp3 import MP3
def load_library(dir):
for root, dirs, files in os.walk("."):
for filename in files:
if filename.lower().endswith(".mp3"):
fullname = os.path.join(root, filename)
print "\n%s" % fullname
try:
audio = MP3(fullname)
for key in audio:
print " %s: %s" % (key, str(audio[key]))
except:
print "Error on %s" % fullname
That is the entire file. I am running it using
python musiclib.py
I suspect it's because you're mixing tabs and spaces. When I copy and paste your code and look at it, I see:
' class Track:'
' \tdef __init__(self, artist, title, album=None):'
' \t\tself.artist = str(artist)'
' self.title = str(title)'
' self.album = album'
' '
' \tdef __str__(self):'
' \t\treturn self.artist + " " + self.title + " " + self.album'
' '
' \tdef set_album(self, album):'
' \t\tself.album = album'
Mixing tabs and spaces confuses Python about how far code is indented. Switch to using four spaces for indentation, and run your code using python -tt yourprogramname.py to confirm this diagnosis.
Related
I am expected to ensure the code is written without unnecessary lines of code. Is there a way to refactor this and get the same output?
def format_name(first_name, last_name):
if len(first_name) > 0 and len(last_name) > 0:
return("Name: " + last_name + ", " + first_name)
elif len(first_name) > 0 or len(last_name) > 0:
return("Name: " + first_name + last_name)
else:
empty_string = ""
return empty_string
return string
print(format_name("Ernest", "Hemingway"))
# Should return the string "Name: Hemingway, Ernest"
print(format_name("", "Madonna"))
# Should return the string "Name: Madonna"
print(format_name("Voltaire", ""))
# Should return the string "Name: Voltaire"
print(format_name("", ""))
# Should return an empty string
Without getting "too golfie", this should do the trick:
def format_name(first_name, last_name):
name = f"{first_name}, {last_name}".strip(", ")
return f"Name: {name}" if name else ""
The refactored method tries to allocate the logic of the function in a single if condition.
def format_name(first_name, last_name):
result = ''
sep = ', ' if first_name and last_name else ' '
if first_name or last_name:
result = last_name + sep + first_name
result = 'Name: ' + result.strip()
return result
print(format_name("Ernest", "Hemingway")) # "Name: Hemingway, Ernest"
print(format_name("", "Madonna")) # "Name: Madonna"
print(format_name("Voltaire", "")) # "Name: Voltaire"
print(format_name("", "")) # `empty_string`
Use str.join and filter to build the name string:
def format_name(first_name, last_name):
full_name = ", ".join(filter(None, (last_name, first_name)))
if full_name:
full_name = "Name: " + full_name
return full_name
How can I print return from functiion CheckTitle() to file .txt? This is code:
class all():
def __init__(self, driver):
super().__init__(driver)
self.full = ()
def CheckTitle(self, Pu, Not, Name):
today = str(date.today())
if self.driver.title == GeneralData.PUBLISHING_PAGE_TITLE:
print(Pu + Name + ', DATE: ' + today)
else:
print(Not + Name + ', DATE: ' + today)
def send_path(self):
with open('E:\PycharmProjects\Test\data\Result.txt', 'w') as f:
for pat in self.full:
f.write(pat)
def CheckTitle(self, Pu, Not, Name):
if self.driver.title == GeneralData.PUBLISHING_PAGE_TITLE:
return(Pu + Name + ', DATE: ' + today)
else:
return(Not + Name + ', DATE: ' + today)
def send_path(self):
with open('E:\PycharmProjects\Test\data\Result.txt', 'w') as f:
for pat in self.full:
f.write(pat)
f.write(CheckTitle('Pu -data','Not -Data','Frank'))
You need to have a return statement in the function.
I am writing a program that keeps track of the animals on a farm and I want to be able to search for an animal by e.g: name, gender, age etc, which all are attributes to the objects. I am a complete noob when it comes to Python so all help is very appreciated.
Here is the code i have so far for this, but it only ads the attribute that is searched for to the list and then prints it. I want to be able to add the entire object to the list and print the whole object through that list.
class Djur:
def __init__(self, art, namn, ålder, kön, gravid):
self.art = art
self.namn = namn
self.age = ålder
self.gender = kön
self.gravid = gravid
def __str__(self):
return ("Art: " + str(self.art) + " " + "\n"
"Namn: " + str(self.namn) + " " + "\n"
"Ålder: " + str(self.age) + " " + "\n"
"Kön: " + str(self.gender) + " " + "\n"
"Gravid: " + str(self.gravid))
def __repr__(self):
return str(self)
try:
val2 = input("Ange sök-text")
l=[]
for x in djurlista:
y = x.art or x.gender or x.namn or x.gravid or x.age
if y == val2:
l.append(x.art)
print(l)
meny()
except ValueError:
print("Var god välj ett giltigt alternativ!")
To create a list with the objects you just need to write l.append(x) instead of l.append(x.art). Now you are just appending the property art.
I'm attempting to convert names from a first name first style to a family name first. The trick is getting it to accept input with or without a middle name.
My code as it stands:
import re
def convertName(oldName):
newName = oldName
while newName == oldName:
newName = re.sub('^ +', '',oldName)
newName = re.sub(' +', ' ',newName)
return newName
def main(firstName, middleName, lastName):
finalName = (lastName + firstName + middleName)
return finalName
name = 0
while name != "":
name = str(input("Name ---- "))
if name == "":
print("Finished")
break
newName = convertName(name)
firstNameSplit = newName.find(" ")
firstName = newName[:firstNameSplit]
lastNameSplit = newName.rfind(" ") + 1
lastName = newName[lastNameSplit:] + ', '
middleNameSplit = newName[firstNameSplit:lastNameSplit]
middleName = middleNameSplit.strip()
finalMiddleName = " " + middleName[0] + '.'
finalName = main(firstName, finalMiddleName, lastName)
print("Result --",finalName)
print()
My current results:
Name ---- joshua example example
Result -- example, joshua e.
Name ---- joshua example
Traceback (most recent call last):
line 37, in 0
builtins.IndexError: string index out of range
Any tips/hints would be much appreciated!!
Eventually found out a working solution in the following:
newName = convertName(name)
firstNameSplit = newName.find(" ")
firstName = newName[:firstNameSplit]
lastNameSplit = newName.rfind(" ") + 1
lastName = newName[lastNameSplit:] + ', '
middleNameSplit = newName[firstNameSplit:lastNameSplit]
middleName = middleNameSplit.strip()
if middleName != "":
finalMiddleName = " " + middleName[0] + '.'
else:
finalMiddleName = ""
finalName = main(firstName, finalMiddleName, lastName)
print("Result --",finalName)
print()
Or you could just do the following:
name = str(input("Name ---- "))
if len(name.split()) == 2:
print("Result -- " + name[name.rfind(" "):] + ", " + name[:name.find(" ")] + " " + name[name.find(" ")+1] + ".")
if len(name.split()) == 1:
print ("Result -- " + name[name.find(" "):] + ", " + name[:name.find(" ")])
else:
print ("Sorry! Invalid name")
This implementation has only been tested in Python 2.7.5.
It uses the string methods .find() and .rfind() to find the indices of the start of the first name, middle name, and last name
len(name.split()) tests how many words are in the name.
Your problem:
string = ""
print(string[0])
returns an error.
so, I fixed your main function, but you'll have to re-write the parser:
def main(firstName, lastName, middleName=""):
if(middleName == ""):
finalName = (lastName + " " + firstName)
else:
finalName = lastName + " " + firstName + " " + middleName[0] + "."
return finalName
class Rating():
def __init__(self, user, item, rating):
self.user = user
self.item = item
self.rating = rating
def __str__(self):
return str(user) + " " + str(item) + " " + str(rating)
def __repr__(self):
return str(user) + " " + str(item) + " " + str(rating)
data = open('data.dat').readlines()
records = ()
for i in data:
user, item, rating = i.split()
r = Rating(user, item, rating)
records += (r,)
print records
data = [A, B, C], I'd expect records to have (<Record> A, <Record> B, <Record> C). But instead it contains (<Record> C, <Record> C, <Record> C)?
You are not using the class attributes, but the global variables you have defined by chance.
return str(user) + " " + str(item) + " " + str(rating)
Should look like
return str(self.user) + " " + str(self.item) + " " + str(self.rating)
Your class's __str__ is reference global names:
def __str__(self):
return str(user) + " " + str(item) + " " + str(rating)
Which will be the last iteration of:
user, item, rating = i.split()
That needs to be fixed to be self.user, self.item etc...
Also I would change your line to be the more efficient and Pythonic:
records = [Rating(*line.split()) for line in data]