Writing a program and need some input - python

I am doing a program about creating a file about golf, it allows only one For. When I run the program I get an error about Golf_File.write(Name + ("\n") ValueError: I/O operation on closed file.
Num_People = int(input("How many golfers are playing?: "))
Golf_File = open('golf.txt', 'w')
for count in range(1,Num_People+1):
Name = input("Enter the player's name: ")
Score = int(input("Enter the player's score: "))
Golf_File.write(Name + ("\n"))
Golf_File.write(str(Score) + ("\n"))
Golf_File.close()

The following will work:
Num_People = int(input("How many golfers are playing?: "))
Golf_File = open('golf.txt', 'w')
for count in range(1,Num_People+1):
Name = input("Enter the player's name: ")
Score = int(input("Enter the player's score: "))
Golf_File.write(Name + ("\n"))
Golf_File.write(str(Score) + ("\n"))
Golf_File.close()
The file should be closed outside the for loop

It is generally considered better to use with statements to handle file objects
Num_People = int(input("How many golfers are playing?: "))
with open('golf.txt', 'w') as Golf_File:
for count in range(1,Num_People+1):
Name = input("Enter the player's name: ")
Score = int(input("Enter the player's score: "))
Golf_File.write(Name + ("\n"))
Golf_File.write(str(Score) + ("\n"))
You can read more about this in the Python documentation about reading and writing files
Also obligatory reminder about the official Python naming standards, capitalized variable names should be avoided

Related

How to assign points in a simple game

I am making a simple game, at the beginning you can choose the amount of players, which is between 2 and 5 (shown below) I am having problem with assigning the initial amount of points, which is 100 points. Also, not sure where to place the code regarding the points in my woring code below.
When I start working on the game, after each dice moevent the score would increase.
players_list= []
max_players= 5
max_players = int(input(" Please, insert the number of players? : "))
while (max_players <2) or (max_players > 5) :
max_players = int(input(" Number of players must be between 2 and 5.Number of players ?"))
players_list = []
while len(players_list) < max_players:
player1 = input(" Enter your first and last name? : ")
players_list.append(player1)
print("Players in the game : ")
print(players_list)
Should I change the players list into a dictionary?
The code with the score system that does not work
score=100
players_list= []
max_players= 5
max_players = int(input(" Please, insert the number of players? : "))
while (max_players <2) or (max_players > 5) :
max_players = int(input(" Number of players must be between 2 and 5.Number of players ?"))
players_list = []
while len(players_list) < max_players:
player1 = input(" Enter your first and last name? : ")
players_list.append(player1)
print("Players in the game : ")
players_list.appened (players)= { score:100}
print(players_list)
print(score)
I'd recommend to use dictionary where keys are player names (assuming player names will be unique) and values will be player's score:
players_dict = {}
score = 100
max_players = -1
while not (2 <= max_players <= 5):
max_players = int(input("Please, insert the number of players: "))
while len(players_dict) < max_players:
player = input("Enter your first and last name: ")
if player in players_dict:
print(f"Player {player} already exists, choose another name")
else:
players_dict[player] = score
print(players_dict)
Prints (for example):
Please, insert the number of players: 1
Please, insert the number of players: 3
Enter your first and last name: John
Enter your first and last name: Adam
Enter your first and last name: John
Player John already exists, choose another name
Enter your first and last name: Lucy
{'John': 100, 'Adam': 100, 'Lucy': 100}
No you don't need to change the list into a dictionary. Rather you probably want to have a list of dictionaries.
TLDR;
I'm not sure if I understand your problem, cause the description is vague tbh.
There's no need to use the input before the while loop.
The user can input something what cannot be parsed into an int, so I'd wrap it into try...except block.
"player_list" is redefined
in the 2nd loop it's not player1, it's the "next" player I guess
you can also keep name and surname in a single string and then skip the split
one way or another it would make sense to keep your player as a dict
Consider renaming players_list to players, typically you don't add the name of the data structure to the variable name
Code:
score=100
players_list= []
max_players= 0
while (max_players <2) or (max_players > 5) :
try:
max_players = int(input(" Number of players must be between 2 and 5.Number of players ?"))
except Exception as e:
print(f"Invalid input: {e}")
while len(players_list) < max_players:
name, surname = input(" Enter your first and last name? : ").split(" ")
player = {"name": name, "surname": surname, "points": score}
players_list.append(player)
print(f"Players in the game : {players_list}")

how will I put the conditionals in file handling python

so this is my code so far (I know it's not that clean forgive me):
name = input("Enter Name: ")
course = input("Enter Course: ")
section = input("Enter Section: ")
sub1 = int(input("Enter 1st Grade: "))
sub2 = int(input("Enter 2nd Grade: "))
sub3 = int(input("Enter 3rd Grade: "))
sub4 = int(input("Enter 4th Grade: "))
sub5 = int(input("Enter 5th Grade: "))
avg = int((sub1+sub2+sub3+sub4+sub5)/5)
print("Average mark:",avg)
if avg >=70:
print("Remarks: Passed")
else:
print("Remarks: Failed")
f = open("test.txt", "w+")
f.write(name)
f.write('\n')
f.write(course)
f.write('\n')
f.write(section)
f.write('\n')
f.write("The average is: ")
f.write(str(avg))
f.write('\n')
f.write("Remarks: ")
f = open("test.txt","r")
print(f.read())
f.close()
and this was supposed to be the example outcome of the txt file:
Juan deal Cruz
IT0011
A
The average is 80
Remarks: Passed
but the problem is that I don't know how to put the remarks on the f.write itself
Use another variable and carry it through to where you want it
passed = avg >= 70
passed_str = "Passed" if passed else "Failed"
print("Remarks: " + passed_str)
...
f.write("Remarks: " + passed_str)
f.write('\n')
Or use an if else like you already did for your print statement

Sorting values in a text file in python [duplicate]

This question already has answers here:
How to sort a list of strings?
(11 answers)
Closed 3 years ago.
I am developing a game and i need to add a leader board to it. I have coded one which allows the user to add high scores, view high scores and erase all high score. Now I need to sort all the scores in order of highest to lowest. Here's my code currently [NOTE: I'm aware that this isn't the best menu but I will change that later on]:
choice = input(str("Would you like to add a high score to the leader board?: "))
if choice == "y":
user1 = input(str("Enter username 1: "))
hs1 = input(str("Enter high score: "))
user2 = input(str("Enter username 2: "))
hs2 = input(str("Enter high score: "))
data1 = user1 + ": " + hs1
data2 = user2 + ": " + hs2
with open("leaderboard.txt","a") as file:
file.write(data1)
file.write("\n")
file.write(data2)
file.write("\n")
print("Data added.")
elif choice == "n":
final_list = []
with open("leaderboard.txt","r") as file:
first_list = file.readlines()
for i in first_list:
final_list.append(i.strip())
print("Leader board")
print("-------------")
for count in range(0,len(final_list)):
print(final_list[count])
else:
with open("leaderboard.txt","w") as file:
file.write(" ")
print("leader board cleared.")
I would like the leader board to be displayed once ordered something like this:
1. James F: 32
2. Harris W: 18
3. Courtney J: 12
Thank you for reading!
I found that i can restructure how the data is saved to the text file using numerical data first like this:
user1 = input(str("Enter username 1: "))
hs1 = input(str("Enter high score: "))
user2 = input(str("Enter username 2: "))
hs2 = input(str("Enter high score: "))
data1 = hs1 + " - " + user1
data2 = hs2 + " - " + user2
Now the data starts with a number, i can simply use .sort on my list to sort them, however they will be sorted lowest to biggest so i had to use .reverse() to flip the list around.

How do i print certain items in a list based on user input in python?

So far the user is supposed to enter their name account number and balance which gets put into list. then I ask for them to input their account number and im supposed to print out their specific number from the list instead of the whole list but cant get it to work.
customers = list()
acctnum = list()
balance= list()
count = 0
while count != 2:
name = input("Enter your name: ")
customers.append(name)
num = int(input("Enter account number: "))
acctnum.append(num)
bal = input("Enter Current Balance:$ ")
print()
balance.append(bal)
count = count + 1
print(customers)
print(acctnum)
print(balance)
personal = int(input("Enter account number: "))
print(personal)
if personal in acctnum:
print(acctnum)
I find dictionaries are useful in applications like this:
accounts = {}
for x in range(2):
name = input("Enter your name: ")
num = int(input("Enter account number: "))
bal = input("Enter Current Balance: $")
accounts[num] = {"name": name, "balance": bal}
print()
for k, v in accounts.items():
print(v["name"] + "'s account " + str(k) + " has $" + v["balance"])
personal = int(input("Enter account number: "))
if personal in accounts:
print("Hello, " + accounts[personal]["name"] + " you have $" + accounts[personal]["balance"])
The data right now is stored in independent lists. You would have to implement using an associative data type such as dictionaries (that are implemented in Python).

Average of marks for three topics

I am trying to create a program that will ask the user for a username and password. If the login details are correct, the program should ask for the students name and then ask for three scores, one for each topic. The program should ask the user if they wish to enter another students details. The program should output the average score for each topic. I cannot work out how to enter the student marks for each topic per student and also how to work out the average for each topic for the class.
Can you please help?
login="teacher"
password="school"
usrnm=input("Please enter your username: ")
pw=input("Please enter your password: ")
if (usrnm==login) and (pw==password):
print("==Welcome to the Mathematics Score Entry Program==")
print("Do you want to enter the students score? Yes/No: ")
option = input()
option = option.title()
student_info = {}
student_data = ['Topic 1 : ', 'Topic 2 : ', 'Topic 3 : ']
while (option != "No"):
student_name = input("Name: ")
student_info[student_name] = {}
score1 = int(input("Please enter the score for topic 1: "))
student_info[student_name][Topic_1] = score1
score2 = int(input("Please enter the score for topic 2: "))
student_info[student_name][Topic_2] = score2
score3 = int(input("Please enter the score for topic 3: "))
student_info[student_name][Topic_3] = score3
print("Do you want to enter the students score? Yes/No: ")
option = input()
option = option.title()
average = sum(student_info.values())/len(student_info)
average = round(average,2)
print ("The average score is ", average)
else:
print("Access denied!")
just keep the marks seperate from the student names
students = []
marks = []
option = ""
while (option != "No"):
students.append(input("Name"))
marks.append([float(input("Mark_Category1:")),
float(input("Mark_Category2:")),
float(input("Mark_Category3:"))])
option = input("Add Another?")
import numpy
print(numpy.average(marks,0))
if you really want to do it without numpy
averages = [sum(a)/float(len(a)) for a in zip(*marks)] # transpose our marks and average each column

Categories

Resources