how to check if objedc has attribute false o true - python

I'm trying to check if any of the students are on probation and if they are, display which student please assist with the error code, the code is meant to check if anyone has violated probation, it also displays an error code, the except is normally key error, but when I was trying to figure out the problem i changed it to keyboard interrupt
if students[Student].is_on_probation:
KeyError: 0
students = {}
try:
while True:
from Student import Student
students['1'] = Student("Jim", "Business", 3.1, False)
viewing = False
viewingchange = input("Would you like to view something: ").lower()
if viewingchange == "y":
viewing = True
elif viewingchange == "yes":
viewing = True
else:
viewing = False
add = input("Would you like to add someone: ")
if add.lower() == "yes" or "y":
adder = str(input("Who would you like to add: "))
major = str(input("What is their major: "))
gpa = float(input("GPA: "))
is_on_probation = bool(input("is on probation: "))
students[str(len(students)+1)] = Student(adder, major, gpa, is_on_probation)
def checking():
if viewing:
checker = input("Would you like to view all students or student a/s: ")
if checker.lower() == "a":
print(students)
checkfor = input("Check for: ")
if checkfor.lower() == "probation":
for Student in range(len(students)):
print("works")
if students[Student].is_on_probation:
print("yeppp")
else:
pass
checkerdouble = False
elif checker.lower() == "s":
searchquery2 = input("And which attribute would you like to search: ")
test = input("Student ID: ")
dude = students[test]
if searchquery2.lower() == "Name".lower():
print(dude.name)
elif searchquery2.lower() == "Major".lower():
print(dude.major)
elif searchquery2.lower() == "GPA".lower():
print(dude.gpa)
elif searchquery2.lower() == "is on probation" or "iop" or "probation".lower():
print(dude.is_on_probation)
checkerdouble = True
checking()
except KeyboardInterrupt:
print("Error code: " + "45345593M3940249525")

Your students dictionary uses string representations of numbers that start at str(1). So the loop should do the same. I think it would be better to just use int keys.
for student_id in map(str, range(1, len(students)):
if students[student_id].is_on_probation:
print(student_id)
This would work but it relies on the dictionary keys being dense. I would prefer to do:
for student_id in sorted(students, key=int):
if students[student_id].is_on_probation:
print(student_id)
Some might object to the indexing, as one can do:
for student_id, student in sorted(students.items(), key=lambda v: int(v[0])):
if student.is_on_probation:
print(student_id)

Related

Stuck while calling functions in a while loop?

My program is supposed to record information for athletes in a race. When I select the option to add a score for an athlete, it calls the input_scores function, but then it won't get out of it? Also, for option "b", I want it to display the message that there's no record available if the list athlete_results is empty. I hope I've explained things ok, I am new to programming so any help is appreciated!
menu = """Choose an option:
'a' = Input score
'b' = Display results
'c' = quit
>
"""
athlete_results = []
choice = input(menu).strip().lower()
def input_scores():
name = input("Name: ").strip().title()
country = input("Country: ").strip().title()
time = input("Time: ").strip()
athlete_results.append({
"Name": name,
"Country": country,
"Time:": time
})
def display_results():
for athlete in athlete_results:
name, country, time = athlete_results.values
print(f"{name}| {country}| {time}s")
while True:
if choice == 'a':
input_scores()
elif choice == 'b':
if athlete_results:
display_results()
elif choice == 'c':
break
else:
print("Invalid option!!!")
Move the line
choice = input(menu).strip().lower()
to a line directly after while True:
while True:
choice = input(menu).strip().lower()
in order to have a chance to change the option or quit.

Creating a menu using a dictionary

I need help with the below code please, I am trying to create a piece of code that displays true or false at the beginning with a given course code using a function. four letters, 3 digits, and a 'space' in between them if that condition is true then the program will ask the user to choose the menu with 6 options using a dictionary. please explain to me where did I go wrong.
Thank you
What I have tried:
def CourseCode(input_word):
COURSES = ['SCIN', 'ENGG', 'MATC', 'BCSE', 'BCMS', 'ENGS', 'MGMT', 'COMM']
VALID_DIGITS = (1, 2, 3, 4, 6)
if user_code == 'SCIN 123':
return True
else:
return False
def user_menu():
add_course = {}
add_course['1'] ="Add new Course:"
add_course[True] = "Course added"
add_course[False]= "Invalid course code: The format is XXXX 111"
list_course = {}
list_course['2'] = "List Course:"
print("SCIN 123", "ENGG 101", "MATC 354", "MATC 355", "BCSE 202", "CCMS 100", "ENGS 202" )
stu_enrol = {}
stu_enrol['3'] = "Enrol Student"
stu_enrol = input("Please enter student family name: ")
stu_enrol[new_student]=[]
print(stu_enrol)
stu_enrol = input(f"Please enter student first initial {new_student}: ")
stu_enrol = input(f"Please enter course to enrol or X to finish {new_student}: ")
if key_data in stu_enrol:
print("Successfully enrolled.")
elif(key_data != add_course ):
print("Sorry you need to enrol in at least two courses")
elif(key_data != stu_enrol):
print("Sorry, already enrolled in that course")
elif(key_data != CourseCode):
print("Sorry, that course does not exist.")
else:
print("Sorry, a maximum of four courses are allowed")
lis_enr_stu = {}
lis_enr_stu['4']={"List Enrolments for a Student"}
lis_all_enr = {}
lis_all_enr['5']={"List all Enrolments"}
user_exit['6'] = "Quit"
if action() is False:
break
input_word = input("Please select menu choice: ")
CourseCode = CourseCode(input_word)

Instantiating classes with user input

I have just started learning about classes. In the examples that I'm learning I notice how everything that gets instantiated is hardcoded into the examples. I wanted to try and figure out if I could instantiate without having to do this, by means of user input.
In line 74/75 my expectation is that print(RecordID_map_PilotID[valUE].flownhours) prints me the number of hours I have chosen to log for a specific instance. Instead I'm confronted with the following pesky error:
Traceback (most recent call last):
File "oop_test.py", line 74, in <module>
RecordID_map_PilotID[valUE].recordflytime(loghours)
AttributeError: 'str' object has no attribute 'recordflytime'
Can anyone please help me understand why what I intend Python to do doesn't actually work?
Thank you!
PilotID_ClassValCalls = {}
RecordID_map_PilotID = {}
class PilotRecord:
department = "Aviation"
asset = "Employee"
assetcategory = "FTE"
flownhours = 0
def __init__(self, pilotid, name, age, licensestatus, licenseexpiration, shiptype, callsign, flownhours):
self.pilotid = pilotid
self.name = name
self.age = age
self.licensestatus = licensestatus
self.licenseexpiration = licenseexpiration
self.shiptype = shiptype
self.callsign = callsign
self.flownhours = flownhours
def __str__(self):
return f"{self.pilotid} has an {self.licensestatus} license with an expiration date of {self.licenseexpiration} with the following callsigns:\n {self.callsign} ."
def recordflytime(self, hours):
self.flownhours = self.flownhours + hours
def Adding_Pilot_Records(): #This definitions created new pilot records and instantiates a new object for each pilot rcord that is created. In addition memory values are stored in Dict
add_records_number = int(input("How many pilot records would you like to add? "))
for eachrecord in range(add_records_number):
record_store = [input("Please provide pilot ID: "), input("Please provide pilot Name: "), int(input("Please provide pilot Age: ")),
input("Please provide pilot licensestatus: "), input("Please provide pilot licenseexpiration: "), input("Please provide pilot shiptype: "), input("Please provide pilot callsign: "), 0]
PilotID_ClassValCalls.update({eachrecord + 1 : record_store[0]})
RecordID_map_PilotID.update({PilotID_ClassValCalls[eachrecord+1]: record_store[0]})
PilotID_ClassValCalls[eachrecord+1] = PilotRecord(record_store[0], record_store[1], record_store[2], record_store[3], record_store[4], record_store[5], record_store[6], record_store[7])
while True == True:
print("Hello, Welcome to the PILOT RECORD DATABASE\n",
"What would you like to do with the Records?:\n\n",
" \t1 - \"Add\"\n",
" \t2 - \"Log\"\n",
" \t3 - \"Delete\"\n",
" \t4 - \"Quit\"\n")
userchoice = str(input().lower().strip())
try:
if userchoice == "1" or userchoice == "add":
Adding_Pilot_Records()
continue
elif userchoice == "2" or userchoice == "log":
while userchoice == "2" or userchoice == "log":
pickarecord = str(input("Which Record ID would you like to create a log for? ")).split()
pickarecord_yesno = input(f"Selected Record >>> {RecordID_map_PilotID[pickarecord[0]]}, Is this the correct record? [Y] [N] [Quit]").upper().split()
userchoice = ""
if pickarecord_yesno[0] == "Q" or pickarecord_yesno[0] == "QUIT":
break
elif pickarecord_yesno[0] == "Y" or pickarecord_yesno[0] == "YES":
userchoice = ""
loghours = int(input(f"How many hours would you like to log?"))
pickarecord = str(pickarecord[0])
for record, valUE in RecordID_map_PilotID.items():
if pickarecord in valUE:
RecordID_map_PilotID[valUE].recordflytime(loghours)
print(RecordID_map_PilotID[valUE].flownhours)
elif pickarecord_yesno[0] == "N" or pickarecord_yesno == "NO":
userchoice = "2"
continue
elif userchoice == "3" or userchoice == "delete":
continue
elif userchoice == "4" or userchoice == "quit":
break
except ValueError:
print("Sorry an Error has occurred")
This is the line causing the error:
RecordID_map_PilotID[valUE].recordflytime(loghours)
You're trying to call .recordflytime() on RecordID_map_PilotID[valUE]. But RecordID_map_PilotID is a dictionary of type str -> str, so RecordID_map_PilotID[valUE] references a string and strings don't have .recordflytime() methods.
I can tell it's a string, because this line is the only line modifying it:
RecordID_map_PilotID.update({PilotID_ClassValCalls[eachrecord+1]: record_store[0]})
So, you're updating one dict with another, with a single key/value pair, the key being PilotID_ClassValCalls[eachrecord+1] and the value record_store[0]. PilotID_ClassValCalls is filled similarly, and its value also typically is record_store[0]. And you fill record store with the result of a call to input(), which is a string.
I would suggest you read some examples on object-oriented programming in Python - I think you're trying to do 'by hand' what is better done with the specific data structures and methods that exist for it in Python.
More generally, it's a good idea to separate the structures that hold and operate on data from the code that gets an processes input. After all, you want to manipulate these objects with direct user input now, but what if you save stuff out to a file and read it back later? Or perhaps call your code from a web page? You'd want to use the same classes, but without the direct calls to input() resulting in your code expecting input on the console.

Why are some variables not defined?

This is what I have to do:
Look up and print the student GPA
Add a new student to the class
Change the GPA of a student
Change the expected grade of a student
Print the data of all the students in a tabular format
Quit the program
import student
import pickle
lookup = 1
change = 2
add = 3
delete = 4
QUIT = 0
FILENAME = 'student.dat'
def main():
students_info = load_students()
choice = 0
load_students()
#add(students_info)
change_grade(students_info)
change_GPA(students_info)
#get_menu_choice()
look_up(students_info)
while choice != QUIT:
choice = get_menu_choice()
if choice == lookup:
look_up(students_info)
elif choice == add:
add(students_info)
elif choice == change:
change(students_info)
elif choice == delete:
delete(students_info)
save_students(students_info)
def load_students():
try:
input_file = open(FILENAME, 'rb')
students_dict = pickle.load(input_file)
input_file.close()
except IOError:
students_dict = {}
print(students_dict)
return students_dict
def get_menu_choice():
print()
print('Menu')
print("-------------------")
print('1. Look up ID')
print('2.....')
choice = int(input("Enter your choice:"))
return choice
def look_up(students_info):
ID = input('Enter ID:')
print(student_info.get(ID, "Not found!"))
## try:
## print(students_info[ID])
## except KeyError:
## print("Not found!")
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
GPA= float(input("New GPA:"))
students=student.Student(ID,GPA,grade,work)
students_info[ID] = students
print ("This",students_info[ID])
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
New_grade = input("Enter new grade:")
students=student.Student(ID,GPA,grade,work)
students_info[ID] = students
#new_grade = students_info[name]
else:
print("Not found!")
def add(students_info):
name = input("Enter the student name:")
ID= input("Enter student's ID:")
GPA= float(input("Enter GPA:"))
grade= input("Enter student's expected grade:")
work = input("Does the student work part time or full time?")
students=student.Student(name,ID,GPA,grade,work)
print(students_info['ID'])
def save_students(students_info):
output_file = open(FILENAME, 'wb')
pickle.dump(students_info, output_file)
output_file.close()
main()
Whenever I tried to change the GPA or grade it's not defined. How could I change one value from the dictionary studens_info?
As gus42 has commented, the errors you are getting are from the lines:
students=student.Student(ID,GPA,grade,work)
You've not defined grade or work in either of the places you do this (nor GPA in change_grade), so it should not be surprising that you're getting an error.
I think there are two ways to fix the issue:
The simplest way is to change your logic from creating a new Student object to modifying the one that already exists. I don't know exactly what the attribute names are in your Student class, but here's a reasonable guess at a solution:
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
GPA= float(input("New GPA:"))
students_info[ID].GPA = GPA # assign new GPA to old student object
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
grade = input("Enter new grade:")
students_info[ID].grade = grade # assign new grade to existing student object
else:
print("Not found!")
The other option is to replace the existing Student object with a new one with some different values. This is close to what your current code, but it only really makes sense if your Student objects are immutable (perhaps because you made the type with namedtuple?). To make it work (where your current code does not), you'll have to load the old values from the old Student object before making the new object:
def change_GPA(students_info):
ID = input("ID:")
if ID in students_info:
new_GPA = float(input("New GPA:"))
old_grade = students_info[ID].grade # load old values
old_work = students_info[ID].work
new_student = students.Student(ID, new_GPA, old_grade, old_work)
students_info[ID] = new_student # replace the old student with a new object
else:
print("Not found!")
def change_grade(students_info):
ID = input("ID:")
if ID in students_info:
new_grade = input("Enter new grade:")
old_GPA = students_info[ID].GPA
old_work = students_info[ID].work
new_student = students.Student(ID, old_GPA, new_grade, old_work)
students_info[ID] = new_student
else:
print("Not found!")

Why doesn't my 'oldUser()' run and why does it start again all the time?

I'm very very new to programming and for a school project (50% of my final grade) I had to create a Python program that did roughly this.
I've had some help from my older brother and my teacher but mainly did it myself with some flow charts etc, so please forgive me if I haven't followed conventional rules and things of this nature, or if my code is messy. I will finalise it, just needed bait of help/support from the pro's.
This is my code and I have an issue with it. Once I have pressed 'y' and then 'y' again on the displayMenu() why doesn't it run oldUser()
Also, if any of you have any suggestion on what could make my code better, or I could improve it would be very helpful and I will take it on board.
import os # allows me to use functions defined elsewhere. os module allows for multi platforming.
import sys
words = []
users = {}
status = ""
def teacher_enter_words():
done = False
print 'Hello, please can you enter a word and definition pair.'
while not done:
word = raw_input('\nEnter a word: ')
deff = raw_input('Enter the definition: ')
# append a tuple to the list so it can't be edited.
words.append((word, deff))
add_word = raw_input('Add another word? (y/n): ')
if add_word.lower() == 'n':
done = True
def student_take_test():
student_score = 0
for pair in words:
print 'Definition:', pair[1]
inp = raw_input('Enter word: ')
student_score += check_error(pair[0], inp)
print 'Correct spelling:', pair[0], '\n'
print 'Your score:', student_score
def check_error(correct, inputt):
len_c = len(correct)
len_i = len(inputt)
# threshold is how many incorrect letters do we allow before a
# minor error becomes a major error.
# 1 - allow 1 incorrect letter for a minor error ( >= 2 becomes major error)
threshold = 1
# immediately check if the words are the same length
num_letters_incorrect = abs(len_c - len_i) # abs() method returns value of x - positive dist between x and zero
if num_letters_incorrect == 0:
for i in xrange(0, len(correct)):
if correct[i] != inputt[i]:
num_letters_incorrect += 1
if num_letters_incorrect <= threshold:
if num_letters_incorrect == 0:
return 2 # no incorrect letter.
else:
return 1 # minor error.
else:
return 0 # major error.
def displayMenu():
status = raw_input('Are you a registered user? y/n?: ')
if status == raw_input == 'y':
oldUser()
elif status == 'n':
newUser()
def newUser():
createLogin = raw_input('Create login name: ')
if createLogin in users:
print '\nLogin name already exist!\n'
else:
createPassw = raw_input('Create password: ')
users[createLogin] = createPassw
print '\nUser created!\n'
def oldUser():
login = raw_input('Enter login name: ')
passw = raw_input('Enter password: ')
if login in users and users[login] == passw:
print '\nLogin successful!\n'
else:
print "\nUser doesn't exist or wrong password!\n"
if __name__ == '__main__':
running = True
while running:
os.system('cls' if os.name == 'nt' else 'clear') # multi-platform, executing a shell command
reg = raw_input('Do you want to start the program? y/n?').lower()
if reg == 'y' or reg == 'yes':
displayMenu()
else: sys.exit(0)
inp = raw_input('Are you a Teacher or a Student? (t/s): ').lower()
if inp == 't' or inp == 'teacher':
teacher_enter_words()
else:
student_take_test()
running = False
raw_input is a function. status == raw_input == 'y' will never be true: that is comparing status with the function, and with 'y'.
I suspect that's simply a typo, and you just meant if status == 'y':

Categories

Resources