I'm trying to take information from the user and then take that info to update a dictionary. It's a part of an exercise I'm doing. I've tried to use .format(var1, var2) with the way you update a dictionary, but when ends up happening is only one part of the dictionary gets updated.
name_grade = {}
while True:
name = raw_input("Please give me the name of the student [q to quit]:")
if name == 'q':
break
else:
grade = raw_input("Give me their grade: ")
name_grade['{}'] = '{}'.format(name, grade)
name_grades = {}
while True:
name = input("Please give me the name of the student [q to quit]:")
if name == 'q':
break
else:
grade = input("Give me their grade: ")
name_grades[name]=grade
print(name_grades)
Are you looking for this or something else?
You can update the dictionary by saying
name_grade[name] = grade
Related
I have some homework which I'm not sure how to finish.
The task given was to make a script which would ask the user to enter his name, after entering it, the script would check if the name entered matches with any of the names on a pre-existing list.
If the name matches the script would ask the user if they would like to delete the name off the list or keep it.
If the name doesn't match with any names on the list, it asks if the user if they'd like to add it on it.
The script should write the list of names in the end.
I wrote it like this:
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
while name in lk:
print("Your name is already in our list.")
if name in lk:
bris = input("Would you like to delete your name off our list?[Y/N]:")
if bris == "Y":
lk.remove(name)
print("Your name was removed.")
print(lk)
break
elif bris == "N":
print("OK!",name,"Your name will be saved.")
print(lk)
break
while name not in lk:
doda = input("Your name is not registered on our list, would you like to add it?[Y/N]:")
if doda == "Y":
lk.append(name)
print("Your name has been added.")
print(lk)
elif doda == "N":
print("Alright, goodbye",name,"!")
break
Issue is, that I have no idea how to stop it once the user chooses to delete their name off the list, it always reads the next while because the deleted name is no longer on the list.
Also, I am very sorry if this looks like poo poo I'm new to coding
If the user needs to be entered only once, why using loop?
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
if name in lk:
print("Your name is already in our list.")
bris = input("Would you like to delete your name off our list?[Y/N]:")
if bris == "Y":
lk.remove(name)
print("Your name was removed.")
print(lk)
elif bris == "N":
print("OK!",name,"Your name will be saved.")
print(lk)
else:
doda = input("Your name is not registered on our list, would you like to add it?[Y/N]:")
if doda == "Y":
lk.append(name)
print("Your name has been added.")
print(lk)
elif doda == "N":
print("Alright, goodbye",name,"!")
Your loop structure is the root of the issue. Since you're using while loops I'm assuming you want your script to loop and keep asking for new inputs. In this case you'll want one loop that you can break out of when you're done entering names based on some user input:
lk = ['Peti','John','Mary','Claire','Hellen']
while keep_looping = 'Y':
# check a name
name = input("Please enter a name: ")
if name in lk:
# name in list logic here
else:
# name not in list logic here
# ask user if the loop should continue. Entering 'N' will break the loop
keep_looping = input("Would you like to try another name? (Y/N): ")
You can reuse your existing logic for checking for names in the list and adding/removing, but you'll also want the name checking logic as an if/else block so only one condition can be met per loop. Otherwise you'll run into the same issue when a name exists and gets removed.
There are other optimizations you can do but I'll let you figure those out on your own.
name = input("Please enter your name:")
lk = ['Peti','John','Mary','Claire','Hellen']
if name in lk:
print("your name already present in list")
k= input(("would you like to delete your name from the list: [y/n]:"))
if k=="y":
lk.remove(name)
print("your name is deleted from the list")
print(lk)
else:
print("your name kept as it is in the list")
else:
print("your name is not present in list")
k= input(("would you like to add your name to the list: [y/n]:"))
if k=="y":
lk.append(name)
print("your name is added to the list")
print(lk)
else:
print("list is kept as it is")
print(lk)
I got myself a python book. Currently, in the book, I am learning about dictionaries. The book gave me an exercise about dictionaries. This is the question.
"Create a program that pairs student's name to his class grade. The user should be able to enter as many students as needed and then get a printout of all students' names and grades. The output should look like this:
Please give me the name of the student (q to quit): [input]
Please give me their grade: [input]
[And so on...]
Please give me the name of the student (q to quit): [input]: q
Okay, printing grades!
Student Grade
Student1 A
Student2 B
[And so on...] "
def student():
studentmarks = {}
while True:
name = raw_input("Please give me the name of the student ('q' to quit):")
if name == "q":
break
elif name.isalpha() == True:
grade = raw_input("Please give me their grade ('q' to quit):")
if grade == "q":
break
elif grade.isalpha() == True:
print "Grade is a number! Please try again"
continue
elif grade.isdigit() == True:
studentmarks = {name: grade}
else:
print "Error, please try again"
continue
else:
print "Please try again. {} is not the right input".format(name)
continue
print studentmarks
continue
student()
I modified the code a bit to test the dictionary. I also use python 2
you made only one mistake witch is when you append the data to dictionary:
studentmarks = {name: grade}
it should be like this :
studentmarks[name] = grade
You're overwriting the dictionary every time you get to this line:
studentmarks = {name: grade}
It should be like this:
studentmarks[name] = grade
I want to create a simple app to Ask user to give name and marks of 10 different students and Store them in dictionary.
so far only key:value from the last input is stored into dictionary.
can you please check my code?
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks = {student_name.title():student_mark}
print(marks)
Your current code has two issues: first, it doesn't save the values of each student inside the loop. Second, it always rewrites the entire dictionary with a single key/value pair, that's why it doesn't work.
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks[student_name.title()] = student_mark
print(marks)
You need your code to be inside your loop. Also the way you put value inside your dict is not right. This should do the trick
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks[student_name] = student_mark
print(marks)
Very new at python and im trying to figure out how to write a program to ask the users to input the courses and teachers into a tuple and then have users input "done" as an end. To finish it off i need to print the tuple. Any tips?
such as:
"Please enter your courses:" math
"Please enter your teacher:" John
"Please enter your courses:" done
('math', 'john', etc...)
Since you want to add values iteratively, tuples will not be the best choice for this since they are immutable, You can use either dictionary or lists.
Using Lists:
arr = []
while True:
course = input("Please enter your courses: ")
teacher = input("Please enter your teacher: ")
if course=='done' or techer=='done':
break
arr.append((course,teacher))
Using Dicts
d = {}
while True:
course = input("Please enter your courses: ")
teacher = input("Please enter your teacher: ")
if course=='done' or techer=='done':
break
d[course]=teacher
The user can't input a tuple directly; you'll have to accept each input separately and assemble them into a tuple yourself:
course = input('enter course: ')
teacher = input('enter teacher:' )
mytuple = course, teacher
lst = []
while True:
course = input("Please enter the courses you are taking this semester: ")
if course == 'done':
break
professor = input("Please enter the professor's name for the course: ")
if professor == 'done':
break
lst.append((course, professor))
def convert(lst):
return tuple(lst)
print(convert(lst))
this is what i came up with, thank you
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)