Issue with int/input/print in homework - python

This is a three part question that I am having issues with....
My output is not giving me the option to input my integer, it is printing "none" on the following line and skipping the option
Ending the file trigger is not working properly
counting the players that I have recorded data for....I honestly don't know where to start on counting inputs
--------------------My Output----------------------
You will be asked to enter players names and scores
When you have no more names, enter End
Enter Player's Name or End to exit program: Randy
Enter Randy 's golf score:
None
------------------My Output END--------------------
My code;
def main():
#introduction to user explaining required information to be entered
print("You will be asked to enter players names and scores")
print("When you have no more names, enter End")
#double blank space
print("\n")
#defined y/n
anotherPlayer = "y"
#define file path to save user input
usersFile = open('golf.txt', 'w')
#
while anotherPlayer == "y":
playerName = input("Enter Player's Name or End to exit program: ")
score = int(input(print("Enter", playerName, "'s golf score: ")))
usersFile.write(playerName + "," + str(score) + "\n")
anotherPlayer = input("Is there another player? y / End: ")
End = usersFile.close()
main()
-----------------end my code--------------------
I need it to say;
---------Assignment output Needed-----------------
You will be asked to enter players names and scores
When you have no more names, enter End
Enter Player's Name or End to exit program: Randy
Enter Randy 's golf score: 50
Enter Player's Name or End to exit program: End
You have written 1 players records to golf.txt
---------End assignment output----------------

Try this:
def main():
# introduction to user explaining required information to be entered
print("You will be asked to enter players names and scores")
print("When you have no more names, enter End")
# double blank space
print("\n")
# defined y/n
anotherPlayer = "y"
# define file path to save user input
usersFile = open('golf.txt', 'w')
#
while anotherPlayer == "y":
playerName = raw_input("Enter Player's Name or End to exit program: ")
score=input("Enter "+ str(playerName)+"'s golf score: ")
usersFile.write(playerName + "," + str(score) + "\n")
anotherPlayer = raw_input("Is there another player? y / End: ")
End = usersFile.close()
main()

You don't need to use print here.
score = int(input(print("Enter", playerName, "'s golf score: ")))
Use this
score = int(input("Enter {}'s golf score: ".format(playerName)))

score = int(input(print("Enter", playerName, "'s golf score: ")))
Should be changed to
score = int(input("Enter {0}'s golf score: ".format(playerName)))
for opening and closing a file in python the efficient method is as follows:
with open("filename", "w") as userFile:
userFile.write(data)
using the with open method will close the file for you when the loop is complete.

You have a problem in the line
score = int(input(print("Enter", playerName, "'s golf score: ")))
You cant put a print function inside the input function and you also can not do it like this:
score = int(input("Enter", playerName, "'s golf score: "))
Because input does not work the same way print does. You should read about formatting in python and do it like this:
score = int(input("Enter {0}'s golf score: ".format(playerName)))

Related

Python 3: My code is suppose to print one name and one score from this file but its prints the name twice and the score twice. Why?

This is the assignment:
The first program will read each player’s name and golf score as keyboard input, then save these as records in a file named golf.txt. (Each record will have a field for the player’s name and a field for the player’s score.)
The second program reads the records from the golf.txt file and displays them.
This is my code so far:
def main():
Continue = 'yes'
golf_file = open('golf.txt', 'a')
while Continue == 'yes':
player_name = input("Input the player's name: ")
player_score = input("Input the player's score: ")
golf_file.write(player_name + "\n")
golf_file.write(str(player_score) + "\n")
Continue = input("Would you like to continue? [yes]: ")
display_file = input("Would you like to display the records from the golf.txt? [yes]: ")
golf_file.close()
if(display_file == 'yes'):
displayfile()
def displayfile():
golf_file = open('golf.txt', 'r')
for line in golf_file:
print("The score of this person is: ",line)
print("The name of this person is: ",line)
golf_file.close()
main()
When the names/scores print it looks like this:
The golf.txt:
You are reading one line (that contains the name), and printing it as the name and the score. Then you read the next line containing a score) and print it as the name and the score again.
You want to alternate treating a line as a name or a score, something like
def displayfile():
with open('golf.txt', 'r') as golf_file:
for name in golf_file:
print("The name of this person is: ", name)
score = next(golf_file)
print("The score of this person is: ", score)
Because golf_file is its own iterator, calling next in the body of the loop advances the file pointer by one line, so that the loop always resumes by reading a name line.
Something a little more symmetric might be
def displayfile():
with open('golf.txt', 'r') as golf_file:
while True:
try:
name = next(golf_file)
score = next(golf_file)
except StopIteration:
break
print("The name of this person is: ", name)
print("The score of this person is: ", score)
Even simpler, though, would be to write each name and score on a single line.
def main():
with open('golf.txt', 'a') as golf_file:
while True:
player_name = input("Input the player's name: ")
player_score = input("Input the player's score: ")
golf_file.write(f"{player_name}\t{player_score}\n")
continue = input("Would you like to continue? [yes]: ")
if continue != 'yes':
break
display_file = input("Would you like to display the records from the golf.txt? [yes]: ")
if display_file == 'yes':
displayfile()
def displayfile():
with open('golf.txt', 'r') as golf_file:
for line in golf_file:
name, score = line.strip().split('\t')
print("The score of this person is: ", name)
print("The name of this person is: ", score)
main()

How am i able to search for inputs in a file and print them in a function

The Springfork Amateur Golf Club has a tournament every weekend. The club president has asked you to write four programs:
A. A program that will read each player's name and golf score as keyboard input, the save these records in a file named golf.txt.(Each record will have a field for the player's name and a field for the player's score)
B. A program that reads the records from the golf.txt file and displays them.
C. A program that searches for a particular record when player's name is given.
D. A program that modifies score of a player.
I've got the first 2 parts down but struggling to complete part C and D
This is what I have so far
def main():
move_on = 'y'
golfScoreFile = open('golfRecords.txt', 'a')
while move_on == 'y' or move_on == 'Y':
pName = input("Enter the player's name: ")
pScore = int(input("Enter the player's score: "))
golfScoreFile.write(pName + "\n")
golfScoreFile.write(str(pScore) + "\n")
move_on = input("Would you like to continue? [y]: ")
displayRecords = input("Would you like to display all the records from golfRecords.txt? [y]: ")
golfScoreFile.close()
if (displayRecords == 'y' or displayRecords == 'Y'):
displayRecs()
else:
searchRecs()
def displayRecs():
golfScoreFile = open('golfRecords.txt', 'r')
lineCount = 1
for line in golfScoreFile:
golfRecLine = lineCount % 2
if (golfRecLine == 0):
print("The score of this person is: ", line)
if (golfRecLine == 1):
print("The name of this person is: ", line)
lineCount = lineCount + 1
golfScoreFile.close()
def searchRecs():
search = input("Enter players name to search: ")
def modscore():
main()
print('Please paste your saved file code:')
file_load_code = input('')
file = open('logs.txt', 'r')
logs = file.read()
if file_load_code in logs:
print('Finding file...')
time.sleep(0.2)
print('Found!')
print('Press enter to fully load the file:')
ENTER = input('')
file.close()
file = open('file_context.txt', 'r')
for x in file:
if file_load_code in x:
print(x)
Try that!

Python running calculations on many user inputs

I want my program to take any number of scores from any number of students, and run calculations on them.
student_number = 1
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
while score != -1:
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
more_student = input("Any more student? (Yes or No): ")
while more_student == "Yes":
student_number = student_number + 1
try:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
except:
print("The score entered is not a number. Please enter it again.")
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
while score != -1:
score = int(input("Please enter Student " + str(student_number) + "'s score (-1: Exit): "))
more_student = input("Any more student? (Yes or No): ")
print("done")
Instead of print("done"), I want to somehow take every input I have received and be able to split it up by student, example output:
Student _ has 4 scores. Their average score is _.
Student _ has 3 scores. Their average score is _.
i'd use a dictionary i guess ? This will allow to collect data for each student, namely.
scores = {}
student = input("Student ? ") # Ask for student
if(student not in scores.keys()): # Create new student if necessary
scores[student] = []
score = int(input("Score ? ")) # Generate & store score for the student
scores[student].append(score)
Then to compute for each student the mean of the scores ... So many possibilities. The easiest one to me:
for student, score_list in scores.items():
nb_scores = len(score_list)
mean_score = sum(score_list)/len(score_list)
print("Student {} had {} scores, with a mean of {}". format(student, nb_scores, mean_score))
I'd just finished typing this up for another question of yours that got deleted -- it looks like the same basic problem as this one.
The approach in a nutshell (as I see the accepted answer to this version of the question is already doing) is to use two nested loops, breaking them when it's time to go to the outer loop.
scores = []
while True:
scores.append([])
while True:
try:
score = int(input(
f"Please enter Student {len(scores)}'s score (-1: Exit): "
))
if score == -1:
break
scores[-1].append(score)
except ValueError:
print("The score entered is not a number. Please enter it again.")
if input("Any more student? (Yes or No): ").lower() != "yes":
break
print(scores)
Please enter Student 1's score (-1: Exit): 78
Please enter Student 1's score (-1: Exit): 34
Please enter Student 1's score (-1: Exit): -1
Any more student? (Yes or No): yes
Please enter Student 2's score (-1: Exit): 45
Please enter Student 2's score (-1: Exit): -1
Any more student? (Yes or No): No
[[78, 34], [45]]
I included two infinite loops that breaks when -1 is entered. A hashmap is used where every Student ID is a key and is initialized with an empty array that stores the marks as the second loop executes itself.
marks = {}
while True:
i = int(input("Enter Student ID or press -1 to exit"))
if i == -1:
break
else:
marks[i] = []
while True:
x = int(input("Enter Mark or press -1 to exit"))
if x!=-1:
marks[i].append(x)
else:
break
for i in marks.keys():
count = len(marks[i])
avg = sum(marks[i])/count
print("Student {} has {} scores. Their average is {}".format(i, count, avg))

output combines scores from all students instead of just the one list after repeat

Where am I going wrong, the first part does exactly what I want. I put the first student in with scores it converts and averages but after repeat, it combines the lists and averages ofoutput all subsequent students.
def determine_grade(score):
if (score > 89):
return "A"
elif (score > 79):
return "B"
elif (score > 69):
return "C"
elif (score > 59):
return "D"
elif (score <= 59):
return "F"
def calc_average(test_scores):
total = 0
for i in range(len(test_scores)):
total = total + test_scores[i]
return total/int(len(test_scores))
def main():
repeat="yes"
test_scores = []
while repeat.lower() == "yes":
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter anther student? yes or no: ")
main()
The thing that is wrong with this piece of code is that when you finished collecting info from one student the info is still left in the list, and was mixed up with another student's info
def main():
repeat="yes"
test_scores = []
while repeat.lower() == "yes":
test_scores.clear()
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter another student? yes or no: ")
main()
You need to clear the list before collecting again.
After this line:
while repeat.lower() == "yes":
put:
print(test_scores)
Run the script and enter marks for a couple of students.
I think you will see why it is summing all the students marks in one go.
By the way, sum(test_scores) will add up the elements of test_scores for you. No need
for a loop. Also try out:
for score in test_scores:
print(score)
In general, when you are tempted to write
for i in range(len(things)):
followed by
things[i]
inside the loop, it is usually easier to write
for thing in things:
do_something_with(thing)
Your code will be shorter, more readable and more efficient.
Replace your main fucntion with this one:
def main():
repeat="yes"
while repeat.lower() == "yes":
test_scores = [] # Inside the while loop so it is new every time
student = input("\nEnter student name: ")
for i in range(2):
score = round(float(input("Enter score: ")))
test_scores.append(score)
average_score = calc_average(test_scores)
print("\nStudent Name: ", student)
for i in range(len(test_scores)):
print("Score: ",test_scores[i], "Grade: ",determine_grade(test_scores[i]))
print("Average: ", average_score, "Student: ",student)
repeat = input("\nEnter anther student? yes or no: ")

How to save the users name and last 3 scores to a text file?

I need to write the last three scores of students and their names into a text file for the teacher's program to read and sort later.
I still don't know how to save the last 3 scores
I have tried this so far:
#Task 2
import random
name_score = []
myclass1= open("class1.txt","a")#Opens the text files
myclass2= open("class2.txt","a")#Opens the text files
myclass3= open ("class3.txt","a")#Opens the text files
def main():
name=input("Please enter your name:")#asks the user for their name and then stores it in the variable name
if name==(""):#checks if the name entered is blank
print ("please enter a valid name")#prints an error mesage if the user did not enter their name
main()#branches back to the main fuction (the beggining of the program), so the user will be asked to enter their name again
class_name(name)#branches to the class name function where the rest of the program will run
def class_name(yourName):
try:#This function will try to run the following but will ignore any errors
class_no=int(input("Please enter your class - 1,2 or 3:"))#Asks the user for an input
if class_no not in range(1, 3):
print("Please enter the correct class - either 1,2 or 3!")
class_name(yourName)
except:
print("Please enter the correct class - either 1,2 or 3!")#asks the user to enter the right class
class_name(yourName)#Branches back to the class choice
score=0#sets the score to zero
#add in class no. checking
for count in range (1,11):#Starts the loop
numbers=[random.randint (1,11),
random.randint (1,11)]#generates the random numbers for the program
operator=random.choice(["x","-","+"])#generates the random operator
if operator=="x":#checks if the generated is an "x"
solution =numbers[0]*numbers[1]#the program works out the answer
question="{0} * {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="+":#checks if the generated operator is an "+"
solution=numbers[0]+numbers[1]#the program works out the answer
question="{0} + {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="-":
solution=numbers[0]-numbers[1]#the program works out the answer
question="{0} - {1}=".format(numbers[0], numbers [1])#outputs the question to the user
try:
answer = int(input(question))
if answer == solution:#checks if the users answer equals the correct answer
score += 1 #if the answer is correct the program adds one to the score
print("Correct! Your score is, {0}".format(score))#the program outputs correct to the user and then outputs the users score
else:
print("Your answer is not correct")# fail safe - if try / else statment fails program will display error message
except:
print("Your answer is not correct")#if anything else is inputted output the following
if score >=5:
print("Congratulations {0} you have finished your ten questions your total score is {1} which is over half.".format(yourName,score))#when the user has finished there ten quetions the program outputs their final score
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(yourName,score))
name_score.append(yourName)
name_score.append(score)
if class_no ==1:
myclass1.write("{0}\n".format(name_score))
if class_no ==2:
myclass2.write("{0}\n".format(name_score))
if class_no ==3:
myclass3.write("{0}\n".format(name_score))
myclass1.close()
myclass2.close()
myclass3.close()
Your program seems to be working just fine now.
I've re-factored your code to follow the PEP8 guidelines, you should really try to make it more clear to read.
Removed the try/except blocks, not needed here. Don't use try/except without a exception(ValueError, KeyError...). Also, use with open(...) as ... instead of open/close, it will close the file for you.
# Task 2
import random
def main():
your_name = ""
while your_name == "":
your_name = input("Please enter your name:") # asks the user for their name and then stores it in the variable name
class_no = ""
while class_no not in ["1", "2", "3"]:
class_no = input("Please enter your class - 1, 2 or 3:") # Asks the user for an input
score = 0
for _ in range(10):
number1 = random.randint(1, 11)
number2 = random.randint(1, 11)
operator = random.choice("*-+")
question = ("{0} {1} {2}".format(number1,operator,number2))
solution = eval(question)
answer = input(question+" = ")
if answer == str(solution):
score += 1
print("Correct! Your score is, ", score)
else:
print("Your answer is not correct")
print("Congratulations {0}, you have finished your ten questions!".format(your_name))
if score >= 5:
print("Your total score is {0} which is over half.".format(score))
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))
with open("class%s.txt" % class_no, "a") as my_class:
my_class.write("{0}\n".format([your_name, score]))
main()

Categories