Home > Enterprise >  How to map user input as number to choice as string
How to map user input as number to choice as string

Time:11-25

How can i get my code on the second to last line to print my choice (as in user and admin) and not the number i have chosen (1/2)

def menu2():
    print("1. user")
    print("2. admin")
menu2()
choice =input("Select role for the user :")
choice=float(choice)
if choice==1:
   print(choice)
elif choice==2:
   print(choice)
print("User role:", end=",")
print(choice)

also is there a way I can connect the last line to the line before without having a comma. Sorry I have a lot of questions I'm new to programming and have no one to help me :(

CodePudding user response:

You need use int() but not float()

def menu2():
    print("1. user")
    print("2. admin")
menu2()
choice =input("Select role for the user :")
choice=int(choice)
role = None
if choice==1:
   role = 'user'
   print(choice)
elif choice==2:
   role = 'admin'
   print(choice)
print("User role:", role) 

CodePudding user response:

You can build a dict mapping choice as a number to the user's role as shown below.

choices = """
1. user
2. admin
""".strip()

num_to_role = dict(line.split('. ', maxsplit=1)
                   for line in choices.split('\n'))

print(num_to_role)
print()

def menu2():
    print(choices)
menu2()
choice =input("Select role for the user: ")
print(choice)
if choice in num_to_role:
    print("User role:", num_to_role[choice])
else:
    print('Invalid option, choose one of:',
          str(list(num_to_role.keys())).replace("'", ""))

Example of a playthrough:

{'1': 'user', '2': 'admin'}

1. user
2. admin
Select role for the user: 1
1
User role: user
  • Related