I am trying to create code to pull from a data sheet. My goal is to find the longest song, songs by year, and songs by an artist. Problem is, that when I run what I currently have I get a value returned of 0. Obviously this is not correct. What ways can I do to solve this? I have linked the data sheet here. Click here!
def longest_song():
pass
def songs_by_year(year):
total=0
with open('music.csv', 'r') as f:
for line in f:
time = line.split(",")
song = time[34]
if song == year:
total = total + 1
return total
def all_songs_by_artist(artist):
total = int(0)
data = open("music.csv", "r")
for line in data:
name = line.split(",")
song = name[2]
if song == artist:
total = total + 1
return total
# --------------------------------------
def menu():
print()
print("1. Identify longest song.")
print("2. Identify number of songs in a given year.")
print("3. Identify all songs by a given artist.")
print("4. You choose something that is interesting and non-trivial.")
print("5. Quit.")
# --------------------------------------
def main():
choice = 0
while (choice != 5):
menu()
choice = int(input("Enter your choice: "))
if (choice == 1):
longest_song()
elif (choice == 2):
year = int(input("Enter desired year: "))
number = songs_by_year(year)
## print("The number of songs from", "{:,d}".format(number))
print(number)
elif (choice == 3):
artist = input("Enter name of artist: ").lower()
all_songs_by_artist(artist)
number = all_songs_by_artist(artist)
print("There are", "{:,d}".format(number))
elif (choice == 4):
pass
elif (choice != 5):
print("That is not a valid option. Please try again.")
# --------------------------------------
main()
You are converting input artist to lowercase but Not changing the artist from the file to lower case, thus no matches.
You are converting the Year to an int but not doing so to the year from the file.
It is difficult to tell if there are other issues, as your code sample is not indented properly.
I'm guessing but I suppose that it should look something like this.
def longest_song(): pass
def songs_by_year(year):
total=0
with open('music.csv', 'r') as f:
for line in f:
time = line.split(",")
song = time[34]
try:
if int(song) == year:
total = total + 1
except:
pass
return total
def all_songs_by_artist(artist):
total = int(0)
with open("music.csv", "r") as data:
for line in data:
name = line.split(",")
song = name[2].lower()
if song == artist:
total = total + 1
return total
# --------------------------------------
def menu():
print()
print("1. Identify longest song.")
print("2. Identify number of songs in a given year.")
print("3. Identify all songs by a given artist.")
print("4. You choose something that is interesting and non-trivial.")
print("5. Quit.")
# --------------------------------------
def main():
choice = 0
while (choice != 5):
menu()
choice = int(input("Enter your choice: "))
if (choice == 1):
longest_song()
elif (choice == 2):
year = int(input("Enter desired year: "))
number = songs_by_year(year)
## print("The number of songs from", "{:,d}".format(number))
print(number)
elif (choice == 3):
artist = input("Enter name of artist: ").lower()
all_songs_by_artist(artist)
number = all_songs_by_artist(artist)
print("There are", "{:,d}".format(number))
elif (choice == 4):
pass
elif (choice != 5):
print("That is not a valid option. Please try again.")
# --------------------------------------
main()
Related
empmangpro = True
employees = []
while empmangpro == True:
try:
empcount = len(employees)
print("--------------------Employee Management System--------------------")
print("")
print("There are "+str(empcount)+" employees in the system.")
print("")
print("------------------------------------------------------------------")
print("1. Add new employee")
print("2. View all employees")
programselection = int(input("Please select your option number: "))
if programselection == 1:
employee = []
employee.append(input("First and Last Name: "))
employee.append(input("Social Security Number: "))
employee.append(input("Phone Number: "))
employee.append(input("Email Address: "))
employee.append(input("Salary:$"))
employees.append(employee)
elif programselection == 2:
i = 0
j = 0
empstr = ""
while i < int(empcount):
while j < 5:
empstr = empstr + employees[i][j]
if j != 4:
empstr = empstr + ", "
j += 1
if i+1 != int(empcount):
empstr = empstr + "\n"
j = 0
i += 1
print(empstr)
print[employees]
elif programselection < 3:
empmangpro = False
else:
print("Please enter valid information")
except ValueError:
print("Please enter valid information")
continue
I have option 1 working where you can add multiple employees to the system, but when I select option 2, nothing happens. It is supposed to print all the employees that I add. What did I do wrong here? I only have been programming for less than a month, so I have still have lots to learn. What am I missing or did wrong?
Is not very clear what you are trying to do at option 2. Try commenting your code in the future. The tabbing in your post was not accurate so I made some guesses. Maybe this will help you with your problem:
empmangpro = True
employees = []
while empmangpro == True:
try:
empcount = len(employees)
print("--------------------Employee Management System--------------------")
print("")
print("There are "+str(empcount)+" employees in the system.")
print("")
print("------------------------------------------------------------------")
print("1. Add new employee")
print("2. View all employees")
programselection = int(input("Please select your option number: "))
if programselection == 1:
employee = []
employee.append(input("First and Last Name: "))
employee.append(input("Soci1al Security Number: "))
employee.append(input("Phone Number: "))
employee.append(input("Email Address: "))
employee.append(input("Salary:$"))
employees.append(employee)
elif programselection == 2:
i = 0
j = 0
empstr = ""
while i < empcount:
print(str(employees[i])+"\n")
i += 1
elif programselection > 2:
empmangpro = False
print("Stopping programm")
else:
print("Please enter valid information")
except ValueError:
print("Please enter valid information")
continue
Also if you want to stop the program use elif programselection > 2: instead of elif programselection < 3:.
You said option 1 works. OK (I see some indentation issues).
For option 2, I'll be honest I did not quite follow your code. If you want option 2 to print all employees, I suggest to create an Employee class. That way, you can print(employee) anywhere.
Can put this into employee.py:
class Employee:
def __init__(self, name): # can add all you need social security, ...
first, last = name.split(' ')
self.first = first # add a new line per new parameter
self.last = last
def __str__(self):
# here you can add all of your logic
# to properly format social security, phone number, etc.
# just be sure to return a string, and not print a string!
return f'{self.last}, {self.first}'
Then in your main file:
import employee # put at top of file
employees = [Employee('John Doe'), Employee('Jane Doe')] # sample data
for e in employees:
print(e)
Output:
Doe, John
Doe, Jane
As for incorrectly spaced:
if programselection == 1:
employee = []
# ...
employees.append(employee)
elif programselection == 2:
And:
except ValueError:
print("Please enter valid information")
continue
Ok so I am creating a program so that the user inputs their plane departure time
if the plane departure time is within 45 minutes of current (strftime) then they can procees to board
else, they are told how long until they can make way to gate
e.g. their plane leaves at 8.00 and current time is 7.00 (they cant board yet) so it says they have to wait for 15 minutes
bag = 0
minute = 0
array = []
f_row = ""
f_col = ""
name = ""
x = 0
from time import strftime
def weight():
global bag
print("Bag checking section")
print("")
bag = int(input("Enter weight of your bag: "))
if bag >= 23:
bag += 1
print("You need to pay £4 per extra KG")
print("New total to pay is: £",bag * 4)
elif bag > 0 and bag < 23:
print("Price: free")
else:
print("Try again")
def exchange():
print("Welcome to our exchange system")
print("")
money = float(input("How much money to exchange: £"))
print("1 for DOLLARS")
print("2 for RUPEE")
choice = input("Option: ")
if choice == "1":
print("£",money,"exchanged to $",round((money * 1.35)))
elif choice == "2":
print("£",money,"exchanged to ₹",round((money * 99.40)))
def boarding():
print("Check to see how long until you can board")
print("")
departure = input("Enter time of flight in 24h format: ")
hour = departure[0]+departure[1]
minute = departure[2]+departure[3]
print(hour,minute)
time = minute - 45
print(time)
def seats():
print("")
print("Choose your seats")
print(" ")
name = input("Enter name: ")
f_row = int(input("Enter row to sit in: "))
f_col = int(input("Enter column number: "))
grid = []
print("")
if array[f_row][f_col] != "empty":
print("Seat taken, try again")
elif array[f_row][f_col] == "empty":
array[f_row][f_col] = name
def make():
for x in range(10):
array.append([])
for y in range(7):
array[x].append("empty")
def show():
for row in range(10):
for col in range(7):
symbol = array[row][col]
print(symbol, end = " ")
print()
#main
while True:
print("")
print(strftime("%H:%M%p"))
print("")
print("1 to weigh bag")
print("2 for exchange")
print("3 for time until you can get on plane")
print("4 for choosing seat")
print("5 to exit program")
print("")
choice = input("Option: ")
print("")
if choice == "1":
weight()
elif choice == "4":
make()
show()
seats()
make()
show()
elif choice == "5":
break
elif choice == "2":
exchange()
elif choice == "3":
strftime("%H:%M%p")
print("")
boarding()
else:
print("Try again")
please note I have just started python and will not understand lots of complex code
if possible can it be reallt basic how to do this? thanks
I want to set a limit to which the user can input names. This is where I got to and got stuck. How would I set a limit of 10 to the names the user can input into the list and restrict them from entering anymore?
names = []
print ('1 = Add Name ')
print ('2 = Display List ')
print ('3 = Quit ')
while True:
option = input('What would you like to do: ')
if option == '1':
name= input('Enter name: ')
names.append(name)
you can do :
if option == '1':
names = [input('Enter name:') for _ in range(10)]
I hope that following script can help you:
# libraries
import sys
# list variable to store name
names = []
# limits to save name
limit = 10
# function to display menu
def menu():
print("Enter 1 to add Name")
print("Enter 2 to show list")
print("Enter 3 to quit")
choice = int(raw_input("Enter your choice : "))
return choice
# running for infinite times till user quits
while(True):
choice = menu()
if(choice == 1):
name = raw_input("Enter name to add in list : ")
if(len(names) > 10):
print("You cannot enter more names")
else:
names.append(name)
print(name + " - Name saved successfully.")
if(choice == 2):
print("List of names : ")
print(names)
if(choice == 3):
sys.exit()
I have several lists that each contain objects. All objects have the values "name" and "amount". What I want to do is create a method to update "amount" by first finding the item in the list by user input (enter name to find name) then adding or subtracting a user input value (enter value to add/enter value to subtract).
How would I go about doing this?
This is what I have so far (It's incomplete but it's all I could get done):
Containers = []
Lids = []
Wicks = []
Labels = []
Misc = []
class item(object):
#Constructor
def __init__(self, name, amount):
self.name = name
self.amount = amount
#Accessors
def getName(self):
return self.name
def getAmount(self):
return self.amount
#Mutators
def __str__(self):
return "[Name: " + self.name + \
", Amount: " + self.amount + \
"]"
def addAmount():
found = False
name = input("Enter the name of a container you wish to change: ")
addNewAmount = input("Enter the amount you wish to add: ")
for item in Containers:
if name in item.getName():
found = True
position = Containers.index(name)
print(Containers[position])
if not found:
print("No names match that input.")
def subtractAmount():
update = input("Enter a new amount to subtract: ")
self.amount = amount - update
def addContainer():
name = input("Enter a name for the new container: ")
amount = input("Enter an amount for the new container: ")
return item(name, amount)
def addLid():
name = input("Enter a name for the new lid: ")
amount = input("Enter an amount for the new lid: ")
return item(name, amount)
def addWick():
name = input("Enter a name for the new wick: ")
amount = input("Enter an amount for the new wick: ")
return item(name, amount)
def addLabel():
name = input("Enter a name for the new label: ")
amount = input("Enter an amount for the new label: ")
return item(name, amount)
def addMisc():
name = input("Enter a name for the new misc item: ")
amount = input("Enter an amount for the new misc item: ")
return item(name, amount)
def main():
running = True
while running:
print("Enter a number to start.")
print("1) Add new container 2) Add new lid")
print("3) Add new wick 4) Add new label")
print("5) Add new misc Item 6) Print Inventory")
print("7) Add Amount from item 8) Subtract Amount from item")
print("10) quit")
print("11) print list")
choice = input("> ")
if choice == "1":
Containers.append(addContainer())
elif choice == "2":
Lids.append(addLid())
elif choice == "3":
Wicks.append(addWick())
elif choice == "4":
Labels.append(addLabel())
elif choice == "5":
Misc.append(addMisc())
elif choice == "6":
print("<==========Containers==========>")
for i in Containers:
print(i)
print("<=============Lids=============>")
for i in Lids:
print(i)
print("<=============Wicks============>")
for i in Wicks:
print(i)
print("<============Labels============>")
for i in Labels:
print(i)
print("<==========Misc Items==========>")
for i in Misc:
print(i)
elif choice == "7":
return addAmount()
elif choice == "8":
return subtractAmount()
elif choice == "10":
quit()
elif choice == "11":
print('[%s]' % ', '.join(map(str, Containers)))
else:
print("Invalid entry, please try again.")
if __name__ == "__main__":
main()
There's a couple of issues here. The first is whether you want containers, lids, wicks, etc to all be the same type of object ("item") or whether it would make more sense to have subclasses. Assuming you want them all to be the same ("item") you could adjust your methods according to the code below (I've left out a lot of options for simplicity).
A couple things to note:
"amount" needs to be numerical (int) in order to add or subtract from it correctly
the creation of an item is a function outside the class, and allocates the item to the appropriate list (Containers, Lids)
the "add_amount" function looks through all lists of all items to find a possible match and adjusts the amount accordingly. If a lid and container have the same name, it will modify the first match.
Containers = []
Lids = []
Items = [Containers, Lids]
class item(object):
#Constructor
def __init__(self, name, amount):
self.name = name
self.amount = amount
#Accessors
def getName(self):
return self.name
def getAmount(self):
return self.amount
def __str__(self):
return "[Name: " + self.name + \
", Amount: " + str(self.amount) + \
"]"
def addItem():
global new_item
name = input("Enter a name for the new item: ")
amount = int(input("Enter an amount for the new item: "))
new_item = item(name, amount)
return new_item
def add_amount():
found = False
name = input("Enter the name of the item you wish to change: ")
add_amount = int(input("Enter the amount you wish to add: "))
for itemList in Items:
for item in itemList:
if name == item.getName():
found = True
position = itemList.index(item)
item.amount += add_amount
print(itemList[position])
if not found:
print("No names in match that input.")
def main():
running = True
while running:
print("Enter a number to start.")
print("1) Make a container 2) Make a lid")
print("3) add amount 4) quit")
choice = input("> ")
if choice == "1":
addItem()
print new_item.amount
Containers.append(new_item)
elif choice == "2":
addItem()
print new_item.amount
Lids.append(new_item)
elif choice == "3":
add_amount()
elif choice == "4":
quit()
else:
print("Invalid entry, please try again.")
if __name__ == "__main__":
main()
This might be kind of messy, but should do the work:
def subtractAmount():
containers = [Containers, Lids, Wicks, Labels, Misc]
names = ['Containers', 'Lids', 'Wicks', 'Labels', 'Misc']
print('Select the number of list you want to search for item')
print('\n'.join('{}) {}'.format(str(idx), lst_name) for (idx, lst_name) in enumerate(names, 1)))
selected = input(': ')) - 1
item_name = input('Enter the item name you are looking for: ')
item = None
for value in containers[selected]:
if value.getName().lower() == item_name.lower():
item = value
break
else:
print('No item was found with that name!')
new_amount = input('Enter the new amount for item: ')
item.amount = new_amount
I am a beginner programmer learning python in my intro game development class. The current homework assignment is to create a function to read and write files. We have to do it also where we can use user input to find the file directory. The problem I'n currently having is that I can't figure out how to write the function to open and close the files. I'll post my code for any help. Thank you. I am only focused on Option 8 for the time being.
enter = 0
start = 0
Roger = ()
text_file = ()
line = open("read.txt", "r")
def read_file(line):
for line in text_file:
print(line)
return line
def close_file(text_file):
text_file.close()
return close_file
def update_score(scores, person, amount):
for score in scores:
if score[0].lower() == person.lower():
score[1] += amount
return scores
def update_score1(scores, person, amount):
for score in scores:
if score[0].lower() == person.lower():
score[1] -= amount
return scores
def addition(num1):
return num1 + num1
def square(num):
print("I'm in square")
return num * num
def display(message):
"""Display game instuctions"""
print(message)
def instructions():
"""Display game instuctions"""
print("Welcome to the world's greatest game")
def main():
str1 = ["Roger", 3456]
str2 = ["Justin", 2320]
str3 = ["Beth", 1422]
instructions()
scores = [str1, str2, str3]
start = input("Would you like to view the high score options? y/n ")
if start == "y":
print("""\
Hello! Welcome to the high scores!
Here are the current high score leaders!:
""")
print(scores)
print("""\n\
0 - Sort high scores
1 - Add high score
2 - Reverse the order
3 - Remove a score
4 - Square a number
5 - Add 2 numbers together
6 - Add to a score
7 - Subtract from a score
8 - Read a file
9 - Write to a file
""")
option = int(input("Please enter your selection "))
while option < 8:
print(scores)
if option == 0:
scores.sort()
print("These are the scores sorted alphabetically")
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 1:
print(scores)
print("Please enter your name and score; After entering your name, hit the return key and enter your score")
name = input()
score = int(input())
entry = (name,score)
scores.append(entry)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 2:
print(scores)
scores.reverse()
print("\nHere are the scores reversed")
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 3:
print(scores)
print("Please enter the high score you would like to remove. After typing the name, hit the return key and enter the score")
name1 = input()
score1 = int(input())
remove = (name1,score1)
scores.remove(remove)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 4:
val = int(input("Give me a number to square"))
sqd = square(val)
print(sqd)
option = option = int(input("Please enter your selection"))
elif option == 5:
val0 = int(input("Give me one number"))
val1 = int(input("Give me another number"))
addi = (val0 + val1)
print(addi)
option = option = int(input("Please enter your selection"))
elif option == 6:
print(scores)
sc0 = input("Please enter player whose score you would like to increase. ")
sc1 = int(input("Please enter the amount would would like to add to their score. "))
scores = update_score(scores, sc0, sc1)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 7:
sc2 = input("Please enter player whose score you would like to decrease. ")
sc3 = int(input("Please enter the amount you would like to subtract from their score. "))
scores = update_score1(scores, sc2, sc3)
print(scores)
while option <= 8:
if option == 8:
print (line)
text_file.close()
option = option = int(input("Please enter your selection"))
main()
Function to return a file's contents:
def read_file(filename):
return open(filename).read()
To write to a file:
def write_file(filename, toWrite):
file = open(filename, 'w')
file.write(toWrite)
file.close()
Example usage:
stuffInFile = read_file("myfile.txt")
write_file("myfile.txt", "I just wrote this to a file!")