how will I put the conditionals in file handling python - 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

Related

Python: Add an entry in a file and assign an ID automatically

I'm writing a program that prompts users to do some things, and one of those is add a user by prompting user details. The file.txt is as the image below, but I'm stack on how to actually make the user ID work. The next users added should take ID numbers 5, 6, 7, and so on.
When I run the programme, the ID assigned is random. Can you please advice?
The text file is as below: (I'm a beginner in this please be detailed)
file.txt
def new_user():
file = open('file.txt', 'r+')
lines = file.read()
newid = len(lines)
addUserDetail(newid)
file.close()
def addUserDetail(newid):
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
file = open('file.txt', 'r')
line = file.readlines()
count = len(line)
newcount = len(line)+1
newline=("\n" + str(newcount) + " " + firstname + " " + secondname + " " + address1 + " " + address2 + " " + postcode + " " + telephonenumber)
file = open('file.txt', 'a')
file.write(newline)
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
Although I am not entirely sure if I understood your problem correctly, I am assuming that you would like to use newid in addUserDetail before writing the values back.
The newid inside the new_user function isn't actually taking an arbitrary value. It equals the number of characters in the file. This is because of the file.read() returns type str. This can be fixed by using the readlines() function.
The code for the same is as follows:
def new_user():
file = open('file.txt', 'r+')
lines = [i.strip() for i in file.readlines()]
newid = len(lines)
addUserDetail(newid)
file.close()
def addUserDetail(newid):
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
file = open('file.txt', 'r')
line = file.readlines()
newline = ("\n" + str(newid+1) + " " + firstname + " " + secondname + " " + address1 + " " + address2 + " " + postcode + " " + telephonenumber)
file = open('file.txt', 'a')
file.write(newline)
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
I wrote an example for leveraging comma-separated-value (CSV) files for holding your data. This can be better than simply writing data with spaces because its easier to read back later. What do you do when the address itself has spaces?
Python has a handy csv module that can help with the details. So, here is your problem reworked. This isn't exactly the answer, but an alternate option.
import csv
import os
def new_user():
# removed id generation... let add the called routine that updated
# the database do that
addUserDetail()
def addUserDetail():
firstname = input("Please enter first name: ")
secondname = input("Please enter surname: ")
address1 = input("Please enter house number and street name: ")
address2 = input("Please enter city: ")
postcode = input("Please enter postcode: ")
telephonenumber = input("Please enter telephone number: ")
if not os.path.exists('file.txt'):
with open('file.txt', 'w'):
pass
with open('file.txt', 'r+') as file:
user_id = len(file.readlines()) + 1
writer = csv.writer(file)
writer.writerow([user_id, firstname, secondname, address1,
address2, postcode, telephonenumber])
file.close()
while True:
print("1 - Input for new user")
print("2 - Close the programme")
option = int(input("Option: "))
if option == 1:
new_user()
elif option == 2:
print("See you")
exit(2)
else:
print("Your option is incorrect")
The output from adding 2 users is
1,Jen,Dixon,1 A Street,Big City,99999,111-111-111
2,Bradly,Thompson,99 Elm,Small Town,222,9999

Marks Calculator

I keep getting syntax error highlighted on "m" in second row on the variable "mark2".
This is the code I have:
print("Please enter your 5 marks below")
mark1 = float(input("enter mark1: ")
mark2 = float(input("enter mark2: ")
mark3 = float(input("enter mark3: ")
mark4 = float(input("enter mark4: ")
mark5 = float(input("enter mark5: ")
marksList = [mark1, mark2, mark3, mark4, mark5]
print(marksList)
sumofMarks = mark1 + mark2 + mark3 + mark4 + mark5
averageOfMarks = sumofMarks/5
print("The sum of your mark is: "+str(sumofMarks))
print("The sum of your mark is: "+str(averageOfMarks))
mark1 = float(input("enter mark1: "))
^ you missed this
In the next 4 lines as well. It is better to use an IDE (Eg: PyCharm) to catch these errors.

Writing a program and need some input

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

Variable not defined when file updating

I am currently learning Python and I am making a tennis coach program. On the option 3 where you can update it is not working as it says nameUnder is not defined in the else statement. Please help as I really don't understand why its not working. I have also tries it without the split but that to doesn't work
import os, sys
print("Please select an option:")
print("[1] Add a student")
print("[2] Read a students data")
print("[3] Update a students data")
print("[4] Delete a students data")
menuSelect = int(input("Make your number selection: "))
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if menuSelect == 1:
amountDone=0
amounttodo=int(input("Enter the number of contestants you would like to add: "))
while amounttodo>amountDone:
ageOne=int(input("Enter the age of the contestant: "))
if ageOne <= 11:
underFile=open("Under11s.txt","a")
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
underFile.write("\n"+str(nameUnder) + " | " + str(genderUnder) + " | " + str(posUnder))
underFile.close()
amountDone=amountDone+1
elif ageOne >= 12:
overFile=open("Over11s.txt","a")
nameOver=input("Enter the first name of the student: ")
genderOver=input("Enter the gender of the student: ")
posOver=int(input("Input the last position of the student: "))
overFile.write("\n"+str(nameOver) + " | " + str(genderOver) + " | " + str(posOver))
overFile.close()
amountDone=amountDone+1
else:
print("Invalid, Please enter a number")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 2:
print("Enter the file you would like to open.")
print("1) Under 11's")
print("2) Over 11's")
fileToOpen=int(input("Enter the number of your selection: "))
if fileToOpen == 1:
f = open("Under11s.txt", "r")
file_contents = f.read()
print(file_contents)
elif fileToOpen == 2:
f = open("Over11s.txt", "r")
file_contents = f.read()
print(file_contents)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 3:
studentName = input("Enter the student name you are looking for:")
file = open("Under11s.txt","r")
found=False
for line in file:
details = line.split(",")
writefile = open("Under11supdated.txt","a")
details = line.split(",")
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
file.write("\n"+str(nameUnder)[0] + " | " + str(genderUnder)[1] + " | " + str(posUnder)[2])
else:
file.write("\n"+nameUnder[0] + " | " + genderUnder[1] + " | " + posUnder[2])
file.close()
file.close()
os.remove("Under11s.txt")
os.rename("Under11supdated.txt","Under11s.txt")
if found==True:
print("Details updated")
else:
print("That student cannot be found in the file, no changes made")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
else:
print("Sorry, this option is not available yet!")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nameUnder only gets defined if this statement is true if details[0] == studentName:
Not a 100% of your logic here, but make sure to set nameUnder= "" before the if statement so the variable is declared and can be used in your else clause.
I would recommend you to structure your code with functions for the each options etc., will make it easier to read and possible reuse some of the code.
Partly updated code:
writefile = open("Under11supdated.txt","a")
details = line.split(",")
nameUnder = ""
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")

Python IF Statement not being displayed [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
currently I am getting to grips with Python and I am trying to produce a small script, however I am having issues with an IF statement, ideally I would like it so if the user inputs an "N" or 'n' for "No" then I like this sentence to be displayed "Thank you for using FinalGrade. Goodbye." However, it only loops back and reacts as if I had entered "Y", allowing another student to be inputted.
Heres my code:
results = []
cont = 'y' or 'Y'
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Institution = str(input("Please Enter the Name of Your Insitution: "))
while cont=='y' or 'Y':
print ("\n")
print ("---------------------------------NEW STUDENT---------------------------------")
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 1 / 2 / 3 / 4'): "))
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
print ("Total Grade Average: %G" % (average))
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
results.append(passed_or_failed)
print ("\n")
print ("%s has: %s" % (Student, passed_or_failed))
print ("\n")
The main issues I am having in my code are shown below:
cont = input('Do you want to keep entering students? Y/N: ')
if cont=='N' or 'n':
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
print ("Thank you for using FinalGrade. Goodbye.")
Is there any solution to this problem? Thank you.
if cont=='N' or 'n':
You need to do either:
if cont in "nN":
or:
if cont in ["n", "N"]:
or even:
if cont.lower() == "n":
Writing what you had if cont=='N' or 'n': would not evaluate correctly as you expect.
This is essentially saying:
if cont is ("N" or "n") then do something
Note: the brackets around ("N" or "n"); this will evaluate to True and then your
if statement becomes: if cont == True: which always evaluates to True.
See:
>>> cont = "Y"
>>> if cont == "N" or "n":
... print "cont is N or n"
...
cont is N or n
Update::
You will also want to change your code structure a bit as well to something like this:
while True:
... most of your code ...
cont = raw_input("Do you want to continue? (Y/N)")
if cont.lower() == "n":
break
Update II: From your comments Here is a complete corrected version of your program:
#!/usr/bin/env python
#FinalGrade
results = []
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Institution = str(input("Please Enter the Name of Your Insitution: "))
while True:
print ("\n")
print ("---------------------------------NEW STUDENT---------------------------------")
print ("\n")
Year = str(input("Please Enter the Year of the Student (For Example, 'Year 1 / 2 / 3 / 4'): "))
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
Student = str(input("Student Full Name: "))
print ("\n")
Grade1 = int(input("Enter Student's First Term Grade: "))
Grade2 = int(input("Enter Student's Second Term Grade: "))
Grade3 = int(input("Enter Student's Third Term Grade: "))
Grade4 = int(input("Enter Student's Fourth Term Grade: "))
average = (Grade1+Grade2+Grade3+Grade4)/4
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
print ("Total Grade Average: %G" % (average))
passed_or_failed = "PASSED"
if average < 40:
passed_or_failed = 'FAILED'
results.append(passed_or_failed)
print ("\n")
print ("%s has: %s" % (Student, passed_or_failed))
print ("\n")
cont = input('Do you want to keep entering students? Y/N: ')
if cont.lower() == "n":
print ("\n")
print ("-----------------------------------------------------------------------------")
print ("\n")
print ("Thank you for using FinalGrade. Goodbye.")
break
Sample run: http://codepad.org/hvoYCXWL
Note that the condition to check for entering more data is properly indented inside the while loop's block. This is important.
if cont=='N' or 'n':
Should be
if cont=='N' or cont == 'n':
Or better
if cont in [ 'N', 'n' ]:

Categories

Resources