user3161743
user3161743

Reputation: 171

Python: Ask user to enter 5 different marks

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?

Upvotes: 1

Views: 3141

Answers (3)

Aamir Rind
Aamir Rind

Reputation: 39689

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

Upvotes: 1

Cu3PO42
Cu3PO42

Reputation: 1473

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

Upvotes: 1

archetipo
archetipo

Reputation: 579

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

Upvotes: 0

Related Questions