The question is Write a program that asks the user to enter 5 different students and their mark out of 100. If the user tries to enter a student twice, the program should detect this and ask them to enter a unique student name (and their mark).
my program is..
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
name = raw_input("Enter a unique name: ")
mark = input("Enter the mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary
my problem is how do you loop the else: code if the user keeps entering the same name and mark?
You mix input and raw_input, that's a bad thing. Usually you use raw_input in Python 2 and input in Python 3. The quick and dirty way to solve your problem is:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = raw_input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
else:
print("You already used that name, enter an unique name.")
print dictionary
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
name = name.strip().lower() # store name in lower case, e.g. aamir and Aamir consider duplicate
if not dictionary.get(name):
mark = input("Enter your mark out of 100: ")
dictionary[name] = mark
count += 1
else:
print "please enter unique name"
print dictionary
Store name in lowercase so that aamir and Aamir both should be consider duplicate
the duplicate check should be performed earlier than step Enter your mark to save one step for end user
i think you only need todo this:
dictionary = {}
count = 0
while count < 5:
name = raw_input("Enter your name: ")
mark = input("Enter your mark out of 100: ")
if name not in dictionary:
dictionary[name] = mark
count = count + 1
print dictionary
Related
I try to create a simple program for tracking students scores. This is my code, but I have no idea how to track students scores. Almost of the students are unknown and will always be different.
I am trying to detect wether the students' score is equal to 10.
name_list = []
enter_name = True
while enter_name:
name = input("Name: ")
name_list.append(name)
if name == "end":
enter_name = False
name_list = name_list[:-1]
#score = 0
#for word in name_list:
#score = int(input(f"{word} = {score}"))
#I am not sure about the last part, i think i turned to wrong direction
You should be using a dictionary keyed on student name. Values should be the student's score as an integer (because you want to compare against a constant value of 10).
As you're going to want integer input from the user, you'll need to validate it in order to avoid unwanted exceptions.
Consider this:
DB = {}
while (name := input('Enter student name: ')) != 'end':
while True:
try:
DB[name] = int(input(f'Enter score for {name}: '))
break
except ValueError:
print('Score should be an integer')
for k, v in DB.items():
print(f'{k} {"Genius" if v >= 10 else v}')
Sample:
Enter student name: Fred
Enter score for Fred: abc
Score should be an integer
Enter score for Fred: 10
Enter student name: Mick
Enter score for Mick: 5
Enter student name: end
Fred Genius
Mick 5
You should use a python dictionary:
students_scores = {}
while True:
name = input("Name: ")
if name == "end":
break
score = int(input("Score: "))
students_scores[name] = score
If you want to know whether a student has a score of 10, you can use if students_scores[student] == 10:.
Basically, you input the names and they are saved to the list. Say I input "a, b, c, d and e. After printing the list it comes out with "a, a, a, a, and a"
Then, when it asks if the student has paid or not, it doesn't matter what value you input, the name won't be moved to the designated list.
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + name + " paid? Input y or n: "
input == raw_input()
if input == "y":
paid_list.append[input]
name_list.next
elif input == "n":
unpaid_list.append[input]
name_list.next
print "The students who have paid are", paid_list
print "The students who have not paid are", unpaid_list
Your populating loop is:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name == raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
You first assign the value received through raw_input to name.
Then, for count from 0 to 4, you check if name is equal to the input, and then, append it to name_list.
Instead of checking the equality by writing name == raw_input(...), what you want is to assign the input value into name.
Therefore, you mustn't use ==, but =.
Your loop should be:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5: #CHANGE BACK TO 45
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
Now here is a more Pythonic way:
names_list = [] # there are more than one name in the list
for _ in range(5): # the loop index is not needed, so I use the anonymous underscore
name = raw_input("Enter the student's name: ")
names_list.append(name)
you can try:
name_list = []
count = 0
name = raw_input("Enter the student's name: ")
while count < 5:
name = raw_input("Enter the student's name: ")
name_list.append(name)
count = count + 1
print "List full"
print name_list
paid_list = []
unpaid_list = []
for names in name_list:
print "Has " + names + " paid? Input y or n: "
input = raw_input()
if input == "y":
paid_list.append[input]
elif input == "n":
unpaid_list.append[input]
Note: raw_input() is not there in python 3.x. Instead use: input() (documentation).
I'm a beginner in python. I have created a database for student in python. I'm not able to get the output for all iterations in dict.
my source code:-
n = int(raw_input("Please enter number of students:"))
student_data = ['stud_name', 'stud_rollno', 'mark1', 'mark2','mark3','total', 'average'] for i in range(0,n):
stud_name=raw_input('Enter the name of student: ')
print stud_name
stud_rollno=input('Enter the roll number of student: ')
print stud_rollno
mark1=input('Enter the marks in subject 1: ')
print mark1
mark2=input('Enter the marks in subject 2: ')
print mark2
mark3=input('Enter the marks in subject 3: ')
print mark3
total=(mark1+mark2+mark3)
print"Total is: ", total
average=total/3
print "Average is :", average
dict = {'Name': stud_name, 'Rollno':stud_rollno, 'Mark1':mark1, 'Mark2':mark2,'Mark3':mark3, 'Total':total, 'Average':average} print "dict['Name']: ", dict['Name'] print "dict['Rollno']: ", dict['Rollno'] print "dict['Mark1']: ", dict['Mark1'] print "dict['Mark2']: ", dict['Mark2'] print "dict['Mark3']: ", dict['Mark3'] print "dict['Total']: ", dict['Total'] print "dict['Average']: ", dict['Average']
if i give no of students as 2, I'm getting dict for 2nd database only and not for 1st one too.
output that i got
Please enter number of students:2
Enter the name of student: a
a
Enter the roll number of student:1
1
Enter the marks in subject 1:1
1
Enter the marks in subject 2:1
1
Enter the marks in subject 3:1
1
Total is:3
Average is :1
Enter the name of student:b
b
Enter the roll number of student:2
2
Enter the marks in subject 1:2
2
Enter the marks in subject 2:2
2
Enter the marks in subject 3:2
2
Total is:6
Average is :2
dict['Name']:b
dict['Rollno']:2
dict['Mark1']:2
dict['Mark2']:2
dict['Mark3']:2
dict['Total']:6
dict['Average']:2
Your current code overwrites dict for every i. In addition, you shouldn't use the name dict as this causes confusion with the data type dict in Python.
One solution for you is to use a list of dictionaries, something like the following:
n = int(raw_input("Please enter number of students:"))
all_students = []
for i in range(0, n):
stud_name = raw_input('Enter the name of student: ')
print stud_name
stud_rollno = input('Enter the roll number of student: ')
print stud_rollno
mark1 = input('Enter the marks in subject 1: ')
print mark1
mark2 = input('Enter the marks in subject 2: ')
print mark2
mark3 = input('Enter the marks in subject 3: ')
print mark3
total = (mark1 + mark2 + mark3)
print"Total is: ", total
average = total / 3
print "Average is :", average
all_students.append({
'Name': stud_name,
'Rollno': stud_rollno,
'Mark1': mark1,
'Mark2': mark2,
'Mark3': mark3,
'Total': total,
'Average': average
})
for student in all_students:
print '\n'
for key, value in student.items():
print '{0}: {1}'.format(key, value)
By adding the responses for each new student onto the end of the list, we track all of them in turn. Finally, we print them out using the keys and values stored in the dictionary. This prints, with your inputs:
Name: a
Rollno: 1
Average: 1
Mark1: 1
Mark2: 1
Mark3: 1
Total: 3
Name: b
Rollno: 2
Average: 2
Mark1: 2
Mark2: 2
Mark3: 2
Total: 6
stud = {}
mrk = []
print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")
print("ENTER STUDENT INFORMATION ------------------------ ")
while True :
rno = int(input("enter roll no.. :: -- "))
if rno == 0 :
break
else:
for i in range(3):
print("enter marks ",i+1," :: -- ",end = " ")
n = int(input())
mrk.append(n)
stud[rno] = mrk
mrk = []
print("Records are ------ ",stud)
print("\nRollNo\t Mark1\t Mark2\t Mark3\t Total")
tot = 0
for r in stud:
print(r,"\t",end=" ")
for m in stud[r]:
tot = tot + m
print(m,"\t",end=" ")
print(tot)
tot = 0
How would I stop my code looping after it has added the amount of names the user has inputted instead of doing this:
Add Name
Show list
Quit
Enter your choice : 1
How many names would you like to enter: 2 # How would I set a max of 10 names here?
Enter name: Bob
Enter name: Jim
How many names would you like to enter: # How would I stop this line from repeating?
Actual code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while choice >5 or choice <1:
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
while True:
number=int(input('How many names would you like to enter: '))
name = [input('Enter name:') for _ in range(number)]
names.append(name)
def displayData():
#name.split(",") how would i correctly user split here
print(names)
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Okay, first off, since you only have three menu options, this line:
while choice >5 or choice <1:
Should look like this:
while 3 < choice < 1:
So your displayMenu function looks like this:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
You also said that your addname function was looping forever, this is because you have an infinite while loop.
What you need, as #ettanany said, is a for loop:
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
What this does is ask the user how many names he wants to enter, and then runs the code inside the loop for that amount of times -- so if the user enters the number 9, it will ask for 9 names.
You also said that there should be a maximum of 10 names. We can use a while loop like you did in the displayMenu function to make sure the user enters a number that is 10 or below:
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
Finally, in your displayData function, you want to 'split' the names and print them out.
Just doing print(names) would give us a result like this:
[ 'Spam', 'Eggs', 'Waheed' ]
If we want it to look nice, we need to use a for loop.
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
This will yield a result like this:
Spam
Eggs
Waheed
Which looks much better than just printing out the list.
Complete (fixed) code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
def displayData():
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Instead of while True, you need to use while i < number, so your addname() function should be as follows:
def addname():
i = 0
number = int(input('How many names would you like to enter: '))
while i < number:
name = input('Enter name: ') # We ask user to enter names one by one
names.append(name)
i += 1
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
trying to make a program that prompts user to enter a famous peoples names and continues asking until they type "done" and prints out the list with the names and the number of names. could anyone give me a little help?
def main():
cList = []
cName = []
while cName != ("done"):
cList.append(cName)
cName = input("Enter another name: ")
print("# of names entered: "), [cList]
i = 0
while i < len(cList):
print myList[i]
i += 1
return
main()
Like this?
names = []
while True:
names.append(raw_input('Enter name: '))
if names[-1] == 'done':
names.pop()
break
print("# of names %i" % len(names))
for name in names:
print(name)