返回Random.randint

时间:2019-07-17 15:09:02

标签: python-3.x

创建一个运气函数以返回随机数,以便以后调用。这段代码有效,但这是最有效的方法吗?

import random

def luck_question():
   luck = input("What will you do --> ")
   if luck in "a":
       print("Well done")
       choice = random.randint(1, 50)
       return choice
   elif luck in "b":
       print("Nice Job")
       choice = random.randint(1, 50)
   elif luck in "c":
       print("I see now")
       choice = random.randint(1, 50)
luck = luck_question()
print(f"{luck}")

1 个答案:

答案 0 :(得分:0)

您可以使用dict将上面的代码编写得更短,更清晰,并返回随机int。

import random

def luck_question():
   luck = input("What will you do --> ")

   # This maps the user input `luck` to
   # what should be printed.
   messages_for_inputs = {
       'a': 'Well done',
       'b': 'Nice Job',
       'c': 'I see now',
   }
   # The get call on a dictionary will try to get
   # the desired key (the first argument) and if the
   # key is not found it will return the default (second argument).
   print(messages_for_inputs.get(luck, 'unknown luck'))
   return random.randint(1, 50)

luck = luck_question()
print(f"{luck}")

dict也使添加其他用户输入变得更加容易。