Trying to call read/write functions - python

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!")

Related

How do I apply the sellProduct method to each choice in the menu?

I don't understand why I can't connect the processSale method to the sellProduct method. I think that the classes and other methods don't need any change because I only followed the criterias that were given to me.
#candy machine
class CashRegister:
def __init__(self, cashOnHand = 500,):
if cashOnHand < 0:
self.cashOnHand = 500
else:
self.cashOnHand = cashOnHand
def currentBalance(self):
return self.cashOnHand
def acceptAmount(self, cashIn):
self.cashOnHand += cashIn
class Dispenser:
def __init__(self, numberOfItems = 50, productCost = 50):
if numberOfItems < 0:
self.numberOfItems = 50
else:
self.numberOfItems = numberOfItems
if productCost < 0:
self.productCost = 50
else:
self.productCost = productCost
def getCount(self):
return self.numberOfItems
def getProductCost(self):
return self.productCost
def makeSale(self):
self.numberOfItems -= 1
class MainProgram:
def showMenu(self):
global userInput
print("**** Welcome to Eros' Candy Shop ****")
print("To select an item enter")
print("""1 for Candy
2 for Chips
3 for Gum
4 for Cookies
0 to View Balance
9 to Exit""")
userInput = int(input("Enter your choice: "))
def sellProduct(self, useDispenser = Dispenser(), useRegister = CashRegister()):
try:
self.useDispenser = useDispenser
self.useRegister = useRegister
if self.useDispenser.getCount != 0:
print(f"It costs {self.useDispenser.getProductCost} cents")
cash = int(input("Please enter your payment: "))
change = cash - self.useDispenser.getProductCost
if change < 0:
print("Insufficient money!")
print(f"You need {self.useDispenser.getProductCost - cash} cents more")
return
else:
print(f"Your change is {change} cents")
self.useRegister.acceptAmount(self.useDispenser.getProductCost)
self.useDispenser.makeSale
return
elif self.useDispenser.getCount == 0:
print("The product you chose is sold out! Try the other itmes")
return
except ValueError:
print("You entered an incorrect value. Please use the numbers on the menu only")
def processSale(self):
Register = CashRegister()
Candy = Dispenser()
Chips = Dispenser()
Gum = Dispenser()
Cookies = Dispenser()
while True:
self.showMenu
if userInput == 1:
self.sellProduct(Candy, Register)
elif userInput == 2:
self.sellProduct(Chips, Register)
elif userInput == 3:
self.sellProduct(Gum, Register)
elif userInput == 4:
self.sellProduct(Cookies, Register)
elif userInput == 0:
print("Current Balance is" + str(Register.currentBalance))
elif userInput == 9:
break
mainProgram = MainProgram()
mainProgram.showMenu()
How do i use sellProduct method on userInput 1-4. I get confused when applying the properties of a class and how to connect them. Can you point out what mistakes I made and what other improvements I can do.
here are some points you can improve :
When you call your methods do not forget the parenthesis :
self.useDispenser.getCount()
self.useDispenser.getProductCost()
Create an infinite loop to continuously ask for input within showMenu and delete the one within processSale (for example):
def showMenu(self):
global userInput
userInput = 0
print("**** Welcome to Eros' Candy Shop ****")
while userInput != 9:
print("To select an item enter")
print(MENU)
userInput = int(input("Enter your choice: "))
if userInput < 9:
self.processSale()
But please update the whole program accordingly.
Hope it helps !

Having a Issue with program not working correctly in python

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

Python: Returning array values from a function

I'm trying to understand how to use functions properly. In this code, I want to return 2 arrays for pupil names and percentage scores. However I am unable to return the array variables from the first function.
I've tried using different ways of defining the arrays (with and without brackets, both globally and locally)
This is the relevant section of code for the program
#function to ask user to input name and score
def GetInput():
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
I'm expecting to be asked to enter the values for both arrays.
I'm instead getting:
Traceback (most recent call last):
File "H:/py/H/marks.py", line 35, in <module>
name, mark = GetInput()
File "H:/py/H/marks.py", line 7, in GetInput
names[counter] = input("Please enter the student's name: ")
NameError: global name 'names' is not defined
You need to use dictionary instead of list if your want to use key-value pairs. furthermore you need to return the values outside of for loop. You can try the following code.
Code:
def GetInput():
names = {} # Needs to declare your dict
percentages = {} # Needs to declare your dict
for counter in range(0, 3):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages # Return outside of for loop.
name, mark = GetInput()
print(name)
print(mark)
Output:
>>> python3 test.py
Please enter the student's name: bob
Please enter the student's score %: 20
Please enter the student's name: ann
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{0: 'bob', 1: 'ann', 2: 'joe'}
{0: 20, 1: 30, 2: 40}
If you want to create a common dictionary which contains the students' name and percentages, you can try the following implementation:
Code:
def GetInput():
students = {}
for _ in range(0, 3):
student_name = input("Please enter the student's name: ")
valid = False
while not valid:
student_percentages = int(input("Please enter the student's score %: "))
if student_percentages < 0 or student_percentages > 100:
print("Please enter a valid % [0-100]")
continue
valid = True
students[student_name] = student_percentages
return students
students = GetInput()
print(students)
Output:
>>> python3 test.py
Please enter the student's name: ann
Please enter the student's score %: 20
Please enter the student's name: bob
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{'ann': 20, 'bob': 30, 'joe': 40}
You forgot to set the names and percentages as empty dictionaries so you can use them. Also the "return" should be outside of the for loop.:
def GetInput():
names={}
percentages={}
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
Probably this may help to you.
#function to ask user to input name and score
def GetInput():
names=[]
percentages=[]
for counter in range(0,3):
names.append(input("Please enter the student's name: "))
valid = False
while valid == False:
percentages.append(int(input("Please enter the student's score %: ")))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
print(name,mark)
This is implemented by using two lists. (Not suggested for keeping records. Better use dictionary as done below.)
counter = 10
def GetInput():
names = []
percentage = []
for i in range(counter):
names.append(input("Please enter the student's name: "))
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
return names, percentage
students, marks = GetInput()
The following is implemented by using dictionary, and for this, you do not need the variable counter.
def GetInput():
records = dict()
for i in range(counter):
name = input("Please enter the student's name: ")
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
#percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
records[name] = percent
return records
record = GetInput()
Change the value of counter to how many records you want. This takes care of marks to be between 0 and 100 (included) and to be integer. Its better if you implement it with dictionary.
Wouldn't it be better to have name and percentage in one dict?
#function to ask user to input name and score
def GetInput():
name_percentage = {}
for counter in range(0,10):
name = input("Please enter the student's name: ")
valid = False
while not valid:
percentage = int(input("Please enter the student's score %: "))
if percentage < 0 or percentage > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
name_percentage[name] = percentage
return name_percentage
name_percentage = GetInput()
print(name_percentage)

Python Pulling from Datasheets

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()

How to have python recognize correct value in my code? Dictionaries

for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
Hi, I am trying to create a vocabulary test on python. My code works up until this chunk. After the program prompts the user for their guess, the program will say it is incorrect even if it is the right answer. Is there an error in this code? How can I get around this?
This is what it looks like:
English: white
Spanish: blanco
Incorrect
English: purple
Spanish: morado
Incorrect
Thanks!
Full Code:
def main():
import random
wrongAnswers = []
print("Hello, Welcome to the Spanish-English vocabulary test.")
print(" ")
print("\nAfter the test, this program will create a file of the incorrect answers for you to view")
print("\nTo start, please select from the following options: \nverbs.txt \nadjectives.txt \ncolors.txt \nschool.txt \nplaces.txt") #sk
while True: #SK
selection = input("Insert your selection: ").lower() #user inputs selection #sk
if selection == "verbs.txt" or selection == "adjectives.txt" or selection == 'colors.txt' or selection == 'school.txt' or selection == 'places.txt':
print("You have chosen", selection, "to be tested on.")
break
if False:
print("try again.")
selection = input("Insert your selection: ").lower()
break
file = open(selection, 'r')
dictionary = {}
with file as f:
for line in f:
items = line.rstrip("\n").split(",")
key, values = items[0], items[1:]
dictionary[key] = values
length = len(dictionary)
print(length,'entries found')
n= int(input("How many words would you like to be tested on: "))
while n > length:
print("Invalid. There are only" ,length, "entries")
n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")
for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
if len(wrongAnswers) > 0:
wrong = str(wrongAnswers)
output = input("Please name the file you would like you wrong answers to be saved in: ")
outf = open(output, 'w')
outf.write(wrong)
outf.close()
else:
print("You got all of the problems correct!")
main()

Categories

Resources