How do I use getattr and setattr properly in Python? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I created a class in Python called Student. I need to create five instances of the class, and then be able to return an attribute from an instance of the user's choice, as well as set an attribute to a new value. Here is my code:
class Student:
# Initializer for Student Class
def __init__(self):
self.name = str(input("What is the name of the student? "))
self.id_number = int(input("What is the i.d. number of " + self.name + "? "))
self.gpa = float(input("What is " + self.name + "'s GPA? "))
self.expected_grade = int(input("What is the expected grade of " + self.name + "? "))
self.work_status = str(input("Does " + self.name + " work full-time or part-time? "))
menu = str("1. Look up and print the student GPA." + '\n' +
"2. Add a new student to the class." + '\n' +
"3. Change the GPA of a student." + '\n' +
"4. Change the expected grade of a student." + '\n' +
"5. Print the data of all the students in a tabular format." + '\n' +
"6. Quit the program. ")
# Student list
student_list = []
# Print a list of the instances of Student in alphabetical order
def display_students(self):
Student.student_list.sort()
print("")
for n in Student.student_list:
print(n)
print("")
# Print tabulated format of all instances of Student and attributes
def display_student_info(self):
Student.student_list.sort()
print("Name\tI.D. #\t\tGPA\t\tExpected Grade\t\tEmployment")
print("----------------------------------------------------------")
for name in Student.student_list:
print(name, '\t', getattr(name, "id_number"),
'\t', getattr(name, "gpa"), '\t', getattr(name, "expected_grade"), '\t', getattr(name, "work_status"))
# Menu selection for user
def menu_selection(self):
valid_input = False
user_input = int(input())
while valid_input == False:
try:
if int(user_input) not in range(1, 6):
raise ValueError
else:
valid_input = True
except ValueError:
print("You have entered an invalid selection for the menu. Please enter a number from 1 to 6. ")
user_input = int(input(str()))
# Look up and print student GPA
if user_input == 1:
Student.display_students(self)
name = str(input("Which student would you like to look up the GPA for? "))
print(name + ": " + getattr(Student.name, "gpa"))
# Add a new student to the class
if user_input == 2:
print("")
print("Okay. Let's add a new student to the class. ")
Student.__init__(self)
Student.student_list.append(Student.name)
# Change the GPA of a student
if user_input == 3:
print("")
print("Okay. Let's change the GPA of a student in the class.")
self.display_students(Student)
name = str(input("Which student's GPA would you like to change? "))
new_gpa = str(input("What would you like " + name + "'s new GPA to be? "))
setattr(Student.name, Student.gpa, new_gpa)
# Change the expected grade of a student
if user_input == 4:
print("")
print("Okay. Let's change the expected grade of a student.")
print("Which student's expected grade would you like to change? ")
self.display_students()
name = str(input("Which student's expected grade would you like to change? "))
new_expected_grade = float(input("What would you like " + name + "'s new expected grade to be? "))
setattr(Student, str(Student.expected_grade), new_expected_grade)
# Print the data of all the students in a tabular format
if user_input == 5:
print("")
print("Okay, here is all the data for the currently entered students: ", '\n')
Student.display_student_info(self)
# Quit the program
if user_input == 6:
print("")
print("Okay. Now quitting the program.")
quit()
def main():
count = 0
while count < 5:
Student.__init__(Student)
Student.student_list.append(Student.name)
print("")
count += 1
print("Now that the students information has been entered, you can select from the menu below to alter student data or quit the program."
+ '\n' + "Please make a selection: " + '\n')
print(Student.menu)
Student.menu_selection(Student)
main()
I can not get my getattr or setattr methods working. How can I get them working?

The second argument to getattr and setattr are strings that name the attribute you want. That is, getattr(name, "expected_grade"). Using a variable as the second argument means that the value of the variable is used as the name. Generally, though, there is no real difference between name.expected_grade and getattr(name, 'expected_grade'), although you can supply getattr an optional third argument that is returned (instead of raising an AttributeError) if the named attribute does not exist.
There is nothing in your code to indicate that you need getattr or setattr; just use the dotted name syntax to access the attributes.

Related

I'm having trouble cleaning up this Bad code script. I found a few errors already but I'm currently stuck on this part

I need to correct this script on a bad code. There is 5 total errors. Here's what I've corrected so far. I'm stuck at defining an array in line 3. I've gone through and tried to correct this line by line but have had no luck. Would greatly appreciate a push in the right direction to get this code fixed.
from array import array
students=array()
def getString(prompt, field):
valid=False
while valid==False:
myString=input(prompt)
if (len(myString)>0):
valid=True
else:
print("The student's " + field + " cannot be empty. Please try again.")
return myString
def getFloat(promp, field):
while True:
try:
fNum=float(getString(prompt, field))
break
except ValueError:
print("That is not a valid number for " + field + ", please try again")
return fNum
def addStudent():
first=getString("Enter the student's first name: ", "first name")
last=getString("Enter the student's last name: ", "last name")
major=getString("Enter the student's major: ", "major")
gpa=getFloat("Enter the student's GPA: ", "GPA")
students.append({"first":first,"last":last,"major":major,"gpa":gpa})
def displayStudents():
print("\nCollege Roster:")
print("*************************************************************************")
if (len(students)==0):
print("There are no students to display.")
else:
print("First Name".ljust(20," ")+"Last Name".ljust(30," ")+"Major".ljust(15," ")+"GPA".ljust(6," "))
for i in range(len(students)):
print(students[i]['first'].ljust(20, " "), end="")
print(students[i]['last'].ljust(30, " "), end="")
print(students[i]['major'].ljust(15, " "), end="")
print(str(students[i]['gpa']).ljust(6, " "))
print("*************************************************************************")
def Main():
keepGoing=true
menu="""
*************************************************************************
College Roster System
*************************************************************************
Main Menu:
a) Enter a new Student
b) View all Students
c) Clear Students List
d) Exit
*************************************************************************
Choose an option: """
while keepGoing:
choice=input(menu)
if choice!="":
if choice.lower()=="a":
addStudent()
elif choice.lower()=="b":
displayStudents()
elif choice.lower()=="c":
students.clear()
print("\nThe list of students is cleared.")
elif choice.lower()=="d":
keepGoing=False
else:
print("\nThat is not a valid selection. Please try again.\n")
else:
print("\nYour selection cannot be empty. Please try again.\n")
print("\nOkay, goodbye!!!")
if __name__=="__BC02.py__":
main()
I'm stuck trying to define the array. I know there is also additional errors, but I can't get pass this part.
Here is a version of your code that compiles and seems to run correctly:
students=[]
def getString(prompt, field):
valid=False
while valid==False:
myString=input(prompt)
if (len(myString)>0):
valid=True
else:
print("The student's " + field + " cannot be empty. Please try again.")
return myString
def getFloat(prompt, field):
while True:
try:
fNum=float(getString(prompt, field))
break
except ValueError:
print("That is not a valid number for " + field + ", please try again")
return fNum
def addStudent():
first=getString("Enter the student's first name: ", "first name")
last=getString("Enter the student's last name: ", "last name")
major=getString("Enter the student's major: ", "major")
gpa=getFloat("Enter the student's GPA: ", "GPA")
students.append({"first":first,"last":last,"major":major,"gpa":gpa})
def displayStudents():
print("\nCollege Roster:")
print("*************************************************************************")
if (len(students)==0):
print("There are no students to display.")
else:
print("First Name".ljust(20," ")+"Last Name".ljust(30," ")+"Major".ljust(15," ")+"GPA".ljust(6," "))
for i in range(len(students)):
print(students[i]['first'].ljust(20, " "), end="")
print(students[i]['last'].ljust(30, " "), end="")
print(students[i]['major'].ljust(15, " "), end="")
print(str(students[i]['gpa']).ljust(6, " "))
print("*************************************************************************")
def main():
keepGoing=True
menu="""
*************************************************************************
College Roster System
*************************************************************************
Main Menu:
a) Enter a new Student
b) View all Students
c) Clear Students List
d) Exit
*************************************************************************
Choose an option: """
while keepGoing:
choice=input(menu)
if choice!="":
if choice.lower()=="a":
addStudent()
elif choice.lower()=="b":
displayStudents()
elif choice.lower()=="c":
students.clear()
print("\nThe list of students is cleared.")
elif choice.lower()=="d":
keepGoing=False
else:
print("\nThat is not a valid selection. Please try again.\n")
else:
print("\nYour selection cannot be empty. Please try again.\n")
print("\nOkay, goodbye!!!")
if __name__=="__main__":
main()
Most of the errors were basic typos. For the first error on line 3, I think it's best to use a standard Python list to store the data for each student. A list is created using [].

How can I clear this error message 'expected intended block' in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a problem with my program:(python program)
A = input("What is ur name?") print("Your name is %s" %A)
print("Lets make a little calculations here")
Value1 = input('Lets enter our first value: ') print("Your value is %s" %Value1)
Value2 = input('Now enter the second value: ' ) print("The value you gave was %s" %Value2)
print("Now lets add or multiply this two values together, are yoy ready?")
Sign = input("Please select add(for addition) or multi(for multiplication): ")
print("You have selected %s " %Sign)
print("Loading result values...")
if Sign == '+':
print(Value1 + Value2)
elif Sign == '*':
print(Value1 * Value2)
It gives me the same syntax error any time. please help me.
Your code after a few fixes:
A = input("What is ur name?")
print("Your name is " + A)
print("Lets make a little calculations here")
Value1 = int(input('Lets enter our first value: '))
print("Your value is " + str(Value1))
Value2 = int(input('Now enter the second value: '))
print("The value you gave was " + str(Value2))
print("Now lets add or multiply this two values together, are yoy ready?")
Sign = input("Please select add(for addition) or multi(for multiplication): ")
print("You have selected " + Sign)
print("Loading result values...")
if Sign == '+':
print(Value1 + Value2)
elif Sign == '*':
print(Value1 * Value2)
As I understand from your code, you are new in Python, and you used C before.
In python the input method always return a String.
Also in Python instead of use "%s" in the print you can add your output like that:
print("some text" + variable_name)
The only thing you need to check that that your variables Value1 and Value2 are integers. you can cast your variable to other type in this way:
x = 1
# cast variable into string
y = str(x) # y is a string "1"
# cast variable into int
z = int(y) # z is a integer 1
Also after a if statment you need use tabs, example:
x = 1
if x == 1:
# we are inside the if
print("in if")
print("after if")
Here is the corrected Program
A = input("What is ur name?")
print("Hello %s" %A)
print("Lets make a little calculations here")
Value1 = int(input('Lets enter our first value: '))
print("Your value is %s" %Value1)
Value2 = int(input('Now enter the second value: ' ))
print("The value you gave was %s" %Value2)
print("Now lets add or multiply this two values together,\n are yoy ready?")
Sign = input("Please select addition(+) or\n multiplication(*): ")
print("You have selected %s " %Sign)
print("Loading result values...")
if Sign == '+':
Result = Value1 + Value2
print("Your result = " + str(Result))
elif Sign == '*':
Result = Value1 * Value2
print("Your result = " + str(Result))
Python uses indentation to understand your code and distinguish blocks of codes.
So, indentation is at the beginning of a code line and must be at least one space.
It's is very important in Python (it also make your code readable)
And as you said Python will give you always an error if you skip it.
A = input("What is ur name?") print("Your name is %s" %A)
print("Lets make a little calculations here")
Value1 = input('Lets enter our first value: ') print("Your value is %s" %Value1)
Value2 = input('Now enter the second value: ' ) print("The value you gave was %s" %Value2)
print("Now lets add or multiply this two values together, are yoy ready?")
Sign = input("Please select add(for addition) or multi(for multiplication): ")
print("You have selected %s " %Sign)
print("Loading result values...")
if Sign == '+':
print(Value1 + Value2)
elif Sign == '*':
print(Value1 * Value2)`
One more thing may be helpful for you is that you can write comments in your code, by putting a #write whatever you want here
Comments are words that won't be readed by Python, we use them to keep a notes, or as explanation for people who will read your code in the future.
And also it dosen't matter how many space you keep between lines of codes, Python will skip empty lines

python random numbers and comparison

I'm a new programmer and just starting off with Python. I have the following 2 questions, however, I decided to put them in one post.
When asking to input age, how do I force the program to only accept numbers?
The concept is that after the user has entered their age, the program would pick a random number between 1 and 100 and compare it to the user input, returning either "I'm older than you", "I'm younger than you" or "we are the same age".
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
age = input("How old are you? ")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
random.randint(1, 100)
Try the following
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True: # only numbers
try:
age = int(input("How old are you? "))
except:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
t=random.randint(1, 100)
if t==age:
print("we are the same age") #compare ages
if t<age:
print("I'm younger than you")
if t>age:
print("I'm older than you")
Hi you can try this simply.
import random
name = input("What is your name? ")
print("Hello " + str(name))
while True :
try :
age = int(input("How old are you? "))
break
except :
print("Your entered age is not integer. Please try again.")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
randNumber=random.randint(1, 100)
if randNumber > age :
print("I am older than you")
if randNumber < age :
print("I am younger than you")
else :
print("we are the same age")
Only made few changes to existing code with modifications asked.
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True:
try:
age = int(input("How old are you? "))
except ValueError:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
my_random = random.randint(1, 100)
if my_random > age:
print("Im older than you")
elif my_random < age:
print("I'm younger than you")
else:
print("We are the same age")
Includ a try block around the age part. If the user inputs an non-int answer then it will just pass. I then saved the random int that you generated it and compared it to the age to find if the random int was greater than the age.
To answer your first question, use int() as such:
age = int(input("How old are you? "))
This will raise an exception (error) if the value is not an integer.
To answer your second question, you may store the random number in a variable and use it in comparison to the user's age, using conditional statements (if, elif, else). So for instance:
random.seed() # you need to seed the random number generator
n = random.randint(1, 100)
if n < age:
print("I am younger than you.")
elif n > age:
print("I am older than you.")
else:
print("We are the same age.")
I hope this answers your question. You can refer to the official Python docs for more info on conditional statements.
My guess is that you should convert the variable age into integer. For example:
age = input("How old are you?")
age = int(age)
This should work.
The answer to the 1st question.
x = int(input("Enter any number: "))
To force the program to enter number add int in your input statement as above.

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

Loop to obtain two pieces of user input and save to a global list

Firstly, I am new to Python so please go easy on me... Secondly, I've never used a forum before so if I paste too much code or don't give exactly what you need, forgive me, I shall try my best:
WHAT I NEED MY CODE TO DO:
I need my code to ask the user for an input called moduleName then after moduleName is entered I need it to ask the user for the grade for that specific module. After that is entered I need it to ask again for module then the grade until there are no more to enter where by the user will enter -1 into the module bit to end it. I also need each item to save to a global list I have created. So when I use teh function I have created to view the list it prints out all modules and grades.
MY CODE THUS FAR: (my global list is at top of code named students[])
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
**moduleName= 0
while moduleName != "-1":
moduleName = raw_input("Please enter module name: ")
grade = raw_input ("Please enter students grade for " + moduleName+": ")
students.append(student)**
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
THE OUTPUT I GET:
I have now fixed the loop so it breaks correctly... the only problem I have now is that the moduleName and grade fields save to my global list but only save the last input (being -1) as opposed to the multiple inputs entered... so confused.
The problem may also lie within this function I have created:
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
Again apologies I don't know what's needed on forums etc so go easy on me...
Thank in Advance! =D
I would suggest replacing the while moduleName != "-1": loop with a while True: loop, and then insert this code after asking for the module name:
if moduleName == '-1':
break
This will break out of the while loop when you want it to.
Addressing your second question, the append function is in the else bit of the whole while loop. This means that it only works when the function breaks. You need to put this in the main while loop after you get the input, and get rid of the else.
Also, I don't see student defined anywhere - what is it meant to be?
Here's the code you want:
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == '-1':
break
grade = raw_input("Please enter students grade for " + moduleName+": ")
students.append(student)

Categories

Resources