1

I am creating a dictionary in python in which a user enters his information, such as name and role. Regarding the last two keys, I would like the user to write a simple letter in the input that corresponds exactly to the options I provide.

Example:

`userData= dict() userData["name"]=input("Insert your name and last name: ") userData["role"]=input("What is your role? \nA)Professor \nB) Student [A/B]: ")

#print(userData)`

Then below I'd like to create if statements where if the user enters "A" in the role key, it saves the value as "Professor" in the dictionary, and if he/she/them enters "B" it saves the value as "Student". I tried writing something like this:

if userData["role"]== "A": userData["role"]== "Professor"

Only, in the dictionary, the value that is saved is "A" and not "Professor". How can I get the value I want by making the user type only one letter? Thank you in advance

PS: i'm completely new in Python and this is only an exercise class, please be gentle.

  • Welcome to StackOverflow! Please read [Ask questions, get answers, no distractions](https://stackoverflow.com/tour), [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers), and about [Voting](https://stackoverflow.com/help/privileges/vote-up) and [Accepting](https://stackoverflow.com/help/accepted-answer). – gremur Mar 28 '22 at 15:08

2 Answers2

1

Possible solution is the following:

userData= {}
userData["name"]=input("Insert your name and last name: ")

# start infinite loop until correct role will be entered
while True:
    role=input("What is your role? \nA) Professor \nB) Student\n").upper()
    if role == 'A':
        userData["role"] = "Professor"
        break
    elif role == 'B':
        userData["role"] = "Student"
        break
    else:
        print(f"{role} is incorrect role. Please enter correct role A or B")
        continue

print(userData)

Prints

Insert your name and last name: Gray
What is your role? 
A) Professor 
B) Student 
B
{'name': 'Gray', 'role': 'Student'}
gremur
  • 1,645
  • 2
  • 7
  • 20
0

Another solution that does not require the use of if statements is using another dictionary for role entries.

# define roles dict
roles_dict = {"A": "Professor", "B":"Student"}

# get user data
userData= dict() 
userData["name"]=input("Insert your name and last name: ") 
role_letter=input("What is your role? \nA) Professor \nB) Student [A/B]: ")

# update dict
userData.update({"role": roles_dict[role_letter]})
print(userData)

Prints:

Insert your name and last name: Jayson

What is your role? 
A)Professor 
B) Student [A/B]: A
{'name': 'Jayson', 'role': 'Professor'}
Pantelis
  • 146
  • 1
  • 9