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.
Related
My code below works as long as all of the student's name consists of only two names - ex. Julie Andrews. But, when generating the student's emails, I'm trying to account for the students who have two first names - ex. Mary Jane Stewart. I want it to output something like MJStewart123#gmail.org, vs. what my current code will print, which is MJane123#gmail.com - totally ignoring the student's last name.
After hours of researching Google, I have tried updating my create_emails fx to change my original variable first_last = name.split(" ") to something like first, middle, last = name.split(" ") or first_last = name.split(" ", 2) while also, respectively, updating the line utilizing the attribute .append from its original to student_emails.append(first_last[0][0] + first_last1 + first_last[2]+ last_three_sid + "#gmail.com") or student_emails.append(first[0] + middle[0] + last + last_three_sid + "#gmail.com"). All attempts have obviously returned some form of an error...
The attached Stack Overflow article is the closest thing I could find whose logic might be applicable to what I'm trying to accomplish here, specifically the comment by Manfred, but in reading it, I don't know how to apply what they've done to my program... because I don't quite understand what it is that I'm reading... since I'm such a newbie at all this. I'd appreciate any help you can offer.
student_names = []
def create_names():
count = 1
while count <= 5:
name = input("Enter student name, please. ")
student_names.append(name)
count += 1
create_names()
import random
student_ids = []
def create_ids():
student_id = random.randint(111111,999999)
return student_id
def create_id_list():
for name in student_names:
student_ids.append(create_ids())
create_id_list()
student_emails = []
def create_emails():
for name in student_names:
first_last = name.split(" ")
sid = str(student_ids[student_names.index(name)])
len_sid = len(sid)
last_three_sid = sid[len_sid-3:len_sid]
student_emails.append(first_last[0][0] + first_last[1] + last_three_sid + "#gmail.com") #ignores last index if one is provided.
create_emails()
def student_info():
for name in student_names:
name_pos = student_names.index(name)
print("\n" + "name: " + name)
print("id: " + str(student_ids[name_pos]))
print("email: " + student_emails[name_pos])
student_info()
Finding and first and middle initials in a list of names in python
You could do it like this I guess:
student_names = []
def create_names():
count = 1
while count <= 5:
name = input("Enter student name, please. ")
student_names.append(name)
count += 1
create_names()
import random
student_ids = []
def create_ids():
student_id = random.randint(111111,999999)
return student_id
def create_id_list():
for name in student_names:
student_ids.append(create_ids())
create_id_list()
student_emails = []
def create_emails():
for name in student_names:
email_name = ""
first_last = name.split(" ")
for i, v in enumerate(first_last):
if i > len(first_last)-2:
break
email_name+=v[0]
email_name = email_name+first_last[-1]
sid = str(student_ids[student_names.index(name)])
len_sid = len(sid)
last_three_sid = sid[len_sid-3:len_sid]
student_emails.append(email_name + last_three_sid + "#gmail.com") #ignores last index if one is provided.
create_emails()
def student_info():
for name in student_names:
name_pos = student_names.index(name)
print("\n" + "name: " + name)
print("id: " + str(student_ids[name_pos]))
print("email: " + student_emails[name_pos])
student_info()
Result:
Enter student name, please. Julie Andrews
Enter student name, please. Mary Jane Stewart
Enter student name, please. Jack Hendricks
Enter student name, please. Maria Basset Juliett
Enter student name, please. Marco Hansen
name: Julie Andrews
id: 742536
email: JAndrews536#gmail.com
name: Mary Jane Stewart
id: 823274
email: MJStewart274#gmail.com
name: Jack Hendricks
id: 590875
email: JHendricks875#gmail.com
name: Maria Basset Juliett
id: 982168
email: MBJuliett168#gmail.com
name: Marco Hansen
id: 671240
email: MHansen240#gmail.com
The code is too redundant and could be implemented with some simpler structures.
name construction can use split combined with join function
storage can also use dictionaries to store multiple information about the same object, compared to multiple lists so more concise and efficient
The code itself is not a big problem, mainly the syntax structure requires more skilled,let's encourage each other in our endeavours
try this:
import random
info = []
# You can use for loop if you already know how many times it will loop
for i in range(5):
name = input("Enter student name, please:") # get name
student_id = random.randint(111111, 999999) # get id
name_structure = name.split()
email = "{name_abbr}{last_name}{sid}#gmail.com".format(
name_abbr="".join([item[0] for item in name_structure[:-1]]), # Generate initials
last_name=name_structure[-1], # Generate the last part of the name
sid=str(student_id)[-3:] # Generate the id in the mailbox
)
info.append({"name": name, "id": student_id, "email": email}) # Store to the list, or print directly
# Print Information
for item in info:
print("name:", item["name"])
print("id:", item["id"])
print("email:", item["email"])
print()
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()
I’m finding the Python syntax very confusing, mainly concerning variables. I’m trying to learn it using the Microsoft EDX course but I’m struggling when trying to check if a string from an input is in the variable.
Example 1: Check if a flavor is on the list
# menu variable with 3 flavors
def menu (flavor1, flavor2, flavor3):
flavors = 'cocoa, chocolate, vanilla'
return menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
#print the result
print ("It is", data in menu, "that the flavor is available")
Example 2: Print a message indicating name and price of a car
def car (name, price):
name = input(“Name of the car: “)
price = input (“Price of the car: “)
return (name, price)
print (name, “’s price is”, price)
Also, I would like to know what would be the disadvantage of doing something like this for the example 2:
name = input("name of the car: ")
price = input ("price of the car: ")
print (name,"is", price,"dollars")
Could someone please clarify this to me? Thank you very much!
i didnt understand what your trying to do in first example.
But i can partially understand what your trying to do in second example,
def car ():
name = input("Name of the car: ")
price = input ("Price of the car: ")
return name, price
name,price = car()
print ("{}\'s price is {}".format(name,price))
the above code is the one of the way to solve your problem,
python can return multiple variable
use format function in print statement for clean display.
You dont need function parameters for car. since your taking input from in car function and returning it to the main.
Hope it helps you understand.
Example 1
# menu variable with 3 flavors
def menu():
flavors = 'cocoa, chocolate, vanilla'
return flavors #return flavors instead of menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
# print the result
print ("It is", data in menu(), "that the flavor is available") #menu is a function so invoke with menu () instead of menu
Example 2:
def car(): #no input required since you are getting the input below
name = input('Name of the car: ')
price = input('Price of the car: ')
return (name, price)
name, price = car() #call the function to return the values for name and price
print (name, "’s price is", price)
The below approach works and is faster as compared to calling the function although adding small stuff to form functions allows the program to be modularized, making it easier to debug and reprogram later as well as better understanding for a new programmer working on the piece of code.
name = input("name of the car: ")
price = input("price of the car: ")
print (name, "is", price, "dollars")
Just found how to print the result in the way the exercise required. I had difficulty explaining, but here it is an example showing:
def car(name,price):
name_entry = input("Name car: ")
price_entry = input("Price car: ")
return (name_entry,price_entry)
This is the way to print the input previously obtained
print (car(name_entry,price_entry))
Thank you very much for all the explanations!
I've got a problem while I was doing a program. My program is to create a class student and there are some variables under that and my task is to add the students in a serializable file and delete the students whenever user wants to. I have written the code for adding the students but I am stuck while delete the object. I am very thankful if anyone could help me how to delete a pickled object from a file?
my code is:
import pickle
n = int(input("Enter number of students you want to enter:"))
for i in range(0,n):
name = input("Enter student name: ")
roll = input("Enter roll number: ")
sex = input("Enter sex: ")
sub = input("Enter subject: ")
tot = input("Enter total: ")
s = Student(name,roll,sex,sub,tot)
infile = open("pb.txt","ab")
pickle.dump(s,infile)
infile.close()
and my student class is:
class Student:
def __init__(self,name,roll,sex,sub,tot):
self.name = name
self.roll = roll
self.sex = sex
self.sub = sub
self.tot = tot
One way could be to pickle a list of students. Then when you want to delete, you can read from file, delete as normal e.g. students.remove(), and then pickle again.
Pickle files aren't editable, and they were never meant to be. If you need to track individual pickled items, look at the shelve module - this lets you treat an external collection of (pickled) objects like a dictionary with string keys.
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