class Prog:
def __init__(self, name, course, languange):
self.name = name
self.course = course
self.languange = languange
def show(self):
print("Name:", self.name, "\nCourse:", self.course, "\nLanguage:", self.languange, "\n")
#Complete code
Students = []
#Create and store the students info (objects) in the list Students
number_of = int(input("Number of students?: "))
#Complete code
loop = 0
while loop < antal:
print("Name, course language?") #here I want the user to type the name, course and what programming language he/she is studying
print("The following students are now in the system")
#Complete code
I want the output to be:
Number of students?: 2
Name, course, language?
Alan
P1
Python
Name, course, language?
Jane
P2
Python
The following students are now in the system:
Name : Alan
Course : P1
Language : Python
Name : Jane
Course : P2
Language : Python
I can't seem to give self.name, self.course, self.language the input() value in the list Students = []
I did try to .appendto the list but when I write p.Prog(Students)I get this error message TypeError: __init__() missing 2 required positional arguments: 'course' and 'languange'
This is the code I wrote to store values into the list.
Students = []
number_of = int(input("Number of students?: "))
loop = 0
while loop < number_of:
print("Name, course, language?")
name = input()
course = input()
language = input()
loop += 1
p = Prog(Students)
print("Following students are now in the system.")
p.show()
You need to append to Students.
When you call Prog(), you have to provide the 3 values that you just input as parameters. It's not clear why you thought the Students list would be the proper argument there.
Then when you want to list all the students, you have to loop through the Students list.
Students = []
number_of = int(input("Number of students?: "))
for _ in range(number_of):
name = input('Name: ')
course = input('Course: ')
language = input('Language: ')
p = Prog(name, course, language)
Students.append(p)
print("Following students are now in the system.")
for student in Students:
student.show()
Related
I just cant figure out to use the max command in this program, at this point it keeps telling me that a float value is not iterable
def main():
students = ["Mike", "John", "James", "Dan"]
disGrade = .10
quizGrade = .30
assignGrade = .60
def grade_math(a,b,c):
disGradeFin=disGrade*a
quizGradeFin=quizGrade*b
assignGradeFin=assignGrade*c
averageGrade=disGradeFin+quizGradeFin+assignGradeFin
print(student, "final grade is", averageGrade)
return averageGrade
averageGrade = grade_math
#print(grade_math(100,100,100))
for student in students:
print("Enter", student, "grades")
a=float(input("Please enter student discussion grade."))
b=float(input("Please enter student quiz grade."))
c=float(input("Please enter student assignment grade."))
grade_math(a,b,c)
largestGrade=max(grade_math(a,b,c))
main()
The biggest problem in your code is that your grade_math() function returns a float value, which is a number but not a list or any containers. max() function returns the biggest value in an iterable, but clearly a single number isn't iterable. I guess you want to pick the highiest grade from all students, so I have an idea. Since float isn't iterable, you can put the average grade of each student in a list after one loop. When the whole loop is finished, use max() to get the biggest element in that list. Here's the code:
def main():
students = ["Mike", "John", "James", "Dan"]
students_final_grades = []
disGrade = .10
quizGrade = .30
assignGrade = .60
def grade_math(dis_g, quiz_g, assign_g):
dis_grade_fin = disGrade * dis_g
quiz_grade_fin = quizGrade * quiz_g
assign_grade_fin = assignGrade * assign_g
average_grade = dis_grade_fin + quiz_grade_fin + assign_grade_fin
print(student, "final grade is", average_grade)
return average_grade
average_grade = grade_math
for student in students:
print("Enter", student, "grades")
dis_g = float(input("Please enter student discussion grade."))
quiz_g = float(input("Please enter student quiz grade."))
assign_g = float(input("Please enter student assignment grade."))
students_final_grades.append(grade_math(dis_g, quiz_g, assign_g)) # The code changed
largest_grade = max(students_final_grades)
print(f'The highiest grade of all is:{largest_grade}')
main()
This is one simple solution. However, this code can be optimized more using dict. Change the two lists declared in main() to:
student_name_and_grade = {"Mike":0, "John":0, "James":0, "Dan":0}
and change the append() code in the for loop to:
student_name_and_grade[student] = grade_math(dis_g, quiz_g, assign_g)
after that, change next line to:
largest_grade = max(student_name_and_grade.values())
At last, remember to follow the PEP8 Style Guide when coding :)
Instead of returning the average grade we return the grades itself
def main():
students = ["Mike", "John", "James", "Dan"]
disGrade = .10
quizGrade = .30
assignGrade = .60
def grade_math(a,b,c):
disGradeFin=disGrade*a
quizGradeFin=quizGrade*b
assignGradeFin=assignGrade*c
averageGrade=disGradeFin+quizGradeFin+assignGradeFin
print(student, "final grade is", averageGrade)
return disGradeFin, quizGradeFin, assignGradeFin # This is line that changed
averageGrade = grade_math
#print(grade_math(100,100,100))
for student in students:
print("Enter", student, "grades")
a=float(input("Please enter student discussion grade."))
b=float(input("Please enter student quiz grade."))
c=float(input("Please enter student assignment grade."))
grade_math(a,b,c)
largestGrade=max(grade_math(a,b,c))
main()
I am learning python from scratch and am stuck with classes what I am trying to achieve as follows:
Problem statement: "Collect the data of different students into an array and display."
I am trying to achieve this using classes.
Below is my code which I am trying out. Need help on how to get the values of different question into one single dimensional array.
i.e.
["brittos school", "Ahmedabad", "Francis", "34", " 36", "anthony's school", "Mumbai", "Sam", "45", " 55"]
Where 34 36 are the marks of the subject.
class Mack:
def getmarks(self,numberofsubjects,numberofstudents,sub):
marks=[]
for i in range(numberofstudents):
self.sname=input("Enter your School Name: ")
a.append(marks)
self.city=input("Enter the School City: ")
a.append(marks)
self.name=input("Enter your Name")
a.append(marks)
a=[]
for j in range(numberofsubjects):
a.append(int(input(f"Enter the Marks for {sub[j]} ")))
marks.append(a)
def show(self):
print("My Name is: ",self.name)
print("My City is: ",self.city)
sub=[]
numberofstudents=int(input("Input the number of students"))
numberofsubjects=int(input("Input the number of subjects"))
for i in range(0, numberofsubjects):
ele = input(f"enter the subject name :{i+1}")
sub.append(ele)
ab=Mack()
for i in range(0,numberofstudents):
ab.getmarks(numberofstudents,numberofsubjects,sub)
First of all, you are using the same loop outside the getmarks function and inside it so for example if I input number of students as 2. It will run 4 times which is incorrect. Loop over number of students once. Secondly a is not defined anywhere so if you want the list of all the input I'd suggest creating a as a member variable of this class.
I think this code below is what you need
class Mack:
def getmarks(self,numberofsubjects,numberofstudents,sub):
marks=[]
a = []
for i in range(numberofstudents):
self.sname=input("Enter your School Name: ")
a.append(self.sname)
self.city=input("Enter the School City: ")
a.append(self.city)
self.name=input("Enter your Name")
a.append(self.name)
for j in range(numberofsubjects):
a.append(int(input(f"Enter the Marks for {sub[j]} ")))
marks.append(a)
return a
def show(self):
print("My Name is: ",self.name)
print("My City is: ",self.city)
sub=[]
numberofstudents=int(input("Input the number of students"))
numberofsubjects=int(input("Input the number of subjects"))
for i in range(0, numberofsubjects):
ele = input(f"enter the subject name :{i+1}")
sub.append(ele)
ab=Mack()
result = ab.getmarks(numberofstudents,numberofsubjects,sub)
print(result)
Although this is a very bad approach to do what you are trying to do. What I would suggest is to create a Student Class like.
class Student:
def __init__(self, name, sname, cname, subjects, marks):
self.name = name
self.sname = sname
self.cname = cname
self.subjects = subjects
self.marks = marks
where subjects and marks would lists of subjects and marks. You can also create a dictionary if you want where subject would be key and marks would be value. After that, you can simple create a list of this class and take input for every element of that Student list.
This is a smaller portion of the main code I have been writing. Depending on user selection they can add player informationa and then print the information from the dictionary player roster. I want to store the information and then print in this format but I havent been able to figure out how to do this.
Name ****
Phone Number ****
Jersey Number ****
Im new to dictionaries but I have spent hours reading and searching over the past couple of days about dictionaries and have tried several different ways to do this but failed. I have gotten the closest the way I have it setup now but it still doesnt work right. I feel like I am storing the information incorrectly into the dictionary for starters, any help would be greatly appreciated.
player_roster = {}
def display_roster(self): #Print Roster
if len(player_roster) != 0:
for x in player_roster.keys():
print('Name:', x, 'Phone Number:', player_roster[x])
else: #Print No One on Roster
len(player_roster) == []
print('No names have been entered:')
def add_player(self,): #Enter Members Name
name = input('Enter New Players Name:')
phone_number = input('Enter Players Phone Number:')
jersey_number = int(input('Enter Players Jersey Number'))
player_roster[name] = phone_number, 'Jersey Number', jersey_number
#If I input Toby as Name 444-444 as Phone Number and 3 as Jersey number it outputs like this
Name: Toby Phone Number: ('444-4444', 'Jersey Number', 3)
# I would like it to output like
Name: Toby
Phone Number: 444-4444
Jersey Number: 3
There are some things i would change in your code but to keep this close to what you asked for take a look at this:
def display_roster():
if len(player_roster) != 0:
for x in player_roster.keys():
print('Name:', x)
print('Phone Number:', player_roster[x][0])
print('Jersey Number:', player_roster[x][1])
else:
print('Roster is empty.')
return
player_roster = {}
def add_player():
name = input('Enter New Players Name:\t')
phone_number = input('Enter Players Phone Number:\t')
jersey_number = int(input('Enter Players Jersey Number:\t'))
player_roster[name] = [phone_number, jersey_number]
return
add_player()
display_roster()
# PRINTS:
#Name: Toby
#Phone Number: 444-4444
#Jersey Number: 3
Printing in multiple lines gives you the result you want. As stated in the comments this can also be done with a single print() statement but i do not think compact code makes much difference to you yet.
Further, this len(self.player_roster) == [] line does not make sense. This is as good as simply writing True in a line. The "emptiness" of the team is checked by the else:.
Finally, i would slightly change the way players are stored in the "Roster" dictionary and have it like this: {"Toby": ['444-4444', 3], ...}
I would propose that you replace the print statement to this:
print(" Name: %s \n Phone Number: %s \n Jersey Number: %d") % player_roster[x]
You're pretty much there. The below modification would allow you to print as you need (and is slightly more readable):
class PlayerDictionary():
def __init__(self):
pass
player_roster = {}
def display_roster(self): #Print Roster
if len(self.player_roster) != 0:
for key, value in self.player_roster.iteritems():
print(str(key) + ": " + str(value))
else: #Print No One on Roster
len(self.player_roster) == []
print('No names have been entered:')
def add_player(self,):
self.player_roster['Name'] = input('Enter New Players Name:')
self.player_roster['Phone Number'] = input('Enter Players Phone Number:')
self.player_roster['Jersey Number'] = int(input('Enter Players Jersey Number'))
if __name__ == "__main__":
player = PlayerDictionary()
player.add_player()
player.display_roster()
A slightly more maintainable solution would be to create a class for Player. Set the properties on the object and overload the str function e.g.
class Player(object):
def __init__(self):
self.__name = ""
self.__phone_number = ""
self.__jersey_number = ""
#property
def name(self):
return self.__name
#property
def phone_number(self):
return self.__phone_number
#property
def jersey_number(self):
return self.__jersey_number
#name.setter
def name(self, val):
self.__name = val
#phone_number.setter
def phone_number(self, val):
self.__phone_number = val
#jersey_number.setter
def jersey_number(self, val):
self.__jersey_number = val
def __str__(self):
return ("Name: %s\nPhone Number: %s\nJersey Number: %s" % (str(self.__name), str(self.__phone_number), str(self.__jersey_number)))
if __name__ == "__main__":
player = Player()
player.name = input('Enter New Players Name:')
player.phone_number = input('Enter Players Phone Number:')
player.jersey_number = int(input('Enter Players Jersey Number'))
print(player)
Here is the problem statement:
There is a record of 'n' students, each record having name of student, percent marks obtained in Maths, Physics and Chemistry. The user enters an integer 'n' followed by names and marks for the 'n' students. I am required to save the record in a dictionary data type. The user then enters name of a student and you are required to print the average percentage marks obtained by that student, correct to two decimal places.
what I have tried so far:
num_students = int(raw_input("Please enter number of students:"))
print "you entered %s students" %num_students
student_info = {}
student_data = ['studentname', 'mathmarks', 'physicsmarks', 'chemistrymarks']
for i in range(0,num_students):
for entry in student_data:
student_info[entry] = raw_input(entry )
print student_info
print"please enter student name"
name = raw_input("student name")
if student_info['studentname'] == name:
print "Average student marks:", (int(student_info['mathmarks']) + int(student_info['physicsmarks']) + int(student_info['chemistrymarks']))/3
else:
print"please enter valid name"
This code is working is num_students = 1, However if num_students >1 the code fails.
I am unable to save the entry of each student in dictionary.
I am pretty new to python, would be glad if any one can help me with this.
Actually you need to create a nested dictionary with name as values and another dict as keys, in pretty way the nested dict may look like:
{
'anmol': {'chemistrymarks': 3, 'physicsmarks': 2, 'mathmarks': 1},
'uppal': {'chemistrymarks': 6, 'physicsmarks': 5, 'mathmarks': 4}
}
So you need to add the following lines to create a nested dictionary.
num_students = int(raw_input("Please enter number of students:"))
print "you entered %s students" %num_students
student_info = {}
student_data = ['Math marks : ', 'Physics marks : ', 'Chemistry marks : ']
for i in range(0,num_students):
student_name = raw_input("Name :")
student_info[student_name] = {}
for entry in student_data:
student_info[student_name][entry] = int(raw_input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.
#print student_info
print"Please enter student name ?"
name = raw_input("Student name : ")
if name in student_info.keys():
print "Average student marks : ", str(sum(student_info[name].values())/3.0)
else:
print"please enter valid name"
#youcan use print stmts. acording to your problem
n = raw_input()
grades = []
for entry in range(int(n)):
grades.append([i for i in raw_input().split()])
query = raw_input()
# Find list where first item matches name in query and
# assign grades to queryResult
queryResult = [x[1:] for x in grades if x[0] == query]
total = 0
scores = 0
for x in queryResult:
for y in x:
total += float(y)
scores += 1
print "%.2f" % (float(total/scores))
#Another way
num_of_student = int(raw_input())
dir_student = {}
for i in range(0,num_of_student):
student_info = raw_input()
name = student_info.split()
dir_student[name[0]] = [float(name[1]),float(name[2]),float(name[3])]
find_name = raw_input()
if dir_student.has_key(find_name):
print "{0:.2f}".format(sum(dir_student[find_name])/3.0)
def lists(): #Where list is stored
List = ["Movie_Name",[""],"Movie_Stars",[""],"Movie_Budget",[""]]
print ("Your Movies")
amount_in_list = int(input("How many Movies? "))
x = 1
while x <= amount_in_list:
film = input ("Name of film ... ")
stars = input ("Main stars ...")
Budget = input ("Budget ...")
List.append["Movie_Name"](film)
List.append["Movie_Stars"](stars)
List.append["Movie_Budget"](Budget)
lists()
How do i add the film you enter to the list under the subsetting Movie_Name etc?
A better answer than one which answers your question directly would be: You don't. You definitely need a dictionary for this situation (unless your program develops to a point where you'd prefer creating a custom object)
As a simple demonstration:
def getMovies():
movieinfo = {"Movie_Name": [], "Movie_Stars": [], "Movie_Budget": []}
print ("Your Movies")
amount_in_list = int(input("How many Movies? "))
x = 1
while x <= amount_in_list:
film = input ("Name of film ... ")
stars = input ("Main stars ...")
budget = input ("Budget ...")
movieinfo["Movie_Name"].append(film)
movieinfo["Movie_Stars"].append(stars)
movieinfo["Movie_Budget"].append(budget)
x+=1
return movieInfo
Notice that with a dict you simply use the key string to get the corresponding list (initialized at the start of the function) and append the data as desired.
Edited to provide further information for OP's updated request.
If you want to find a movie's info based on just the movie's name given by the user, you could try something like this:
film = 'The Matrix' # Assuming this is the user's input.
Try:
# The index method will throw an exception if
# the movie cannot be found. If that happens,
# the 'except' clause will execute and print
# the relevant statement.
mIdx = movieinfo['Movie_Name'].index(film)
print '{0} stars {1} and had a reported budget of {2}'.format(
film, movieInfo['Movie_Stars'][mIdx], movieInfo['Movie_Budget'][mIdx])
except ValueError:
print '{0} is not in the movie archives. Try another?'.format(film)
Output:
'The Matrix stars Keanu Reeves and had a reported budget of $80 million'
Or:
'The Matrix is not in the movie archives. Try another?'
I would store the movie information in an object. This way your code will be easier to extend, make changes and reuse. you could easily add methods to your movie class to do custom stuff or add more properties without having to change your code to much.
class Movie:
def __init__(self, name='', actors=[], rating=0 budget=0):
self.name=name
self.actors=actors
self.budget=budget
self.rating=rating
def setName(self, newname):
self.name=newname
def setActors(self, newstars):
self.actors=newstars
def setBudget(self, newbudget):
self.budget=newbudget
def setRating(self, newrating):
self.rating=newrating
# example
mymovies=[]
movie1= Movie('Interstellar',['actor1','actor2','actor3'], 5, 100000)
movie2=Movie()
movie2.setName('other movie')
movie2.setActors(['actor1','actor2','actor3'])
movie2.setBudget(10000)
mymovies.append(movie1)
mymovies.append(movie2)
# or append to your list in a loop