【问题标题】:How to map user input as number to choice as string如何将用户输入作为数字映射到选择作为字符串
【发布时间】:2021-11-24 19:21:36
【问题描述】:

如何让我的代码在倒数第二行打印我的选择(如在用户和管理员中)而不是我选择的数字 (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)

还有一种方法可以在没有逗号的情况下将最后一行连接到前一行。对不起,我有很多问题,我是编程新手,没有人可以帮助我:(

【问题讨论】:

    标签: python if-statement input


    【解决方案1】:

    你需要使用 int() 而不是 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) 
    

    【讨论】:

      【解决方案2】:

      您可以构建一个dict 映射选项作为用户角色的数字,如下所示。

      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("'", ""))
      

      播放示例:

      {'1': 'user', '2': 'admin'}
      
      1. user
      2. admin
      Select role for the user: 1
      1
      User role: user
      

      【讨论】:

        猜你喜欢
        • 2020-06-24
        • 2013-08-30
        • 1970-01-01
        • 2020-12-13
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 2018-03-14
        • 1970-01-01
        相关资源
        最近更新 更多