python - 如何在 Python 3 中将变量设置为随机整数?

标签 python

我对编码还比较陌生,现在正在尝试用 Python 3 构建一个石头剪刀布游戏。这是我目前的代码`

answer = input("To play: type in Rock (r), Paper (p) or Scissors (s)").lower()

if answer == "rock" or answer == "r":
    answer = 1
    print ("You chose Rock!")

elif answer == "paper" or answer == "p":
    answer = 2
    print ("You chose Paper!")

elif answer == "scissors" or answer == "s":
    answer = 3
    print ("You chose Scissors!")

else:
    print ("You didn't pick an option... Make sure you spell it right!")
    rps()

computer = lambda: random.randint(1, 3)
if computer == 1:
    string_computer = "Rock"
elif computer == 2:
    string_computer = "Paper"
elif computer == 3:
    string_computer = "Scissors"
else:
    print ("There must had been a glitch")
    rps()

if answer == computer:
    print(("The computer chose"), string_computer,("so it\'s a draw!"))
elif answer == 1 and computer == 2:
    print(("The computer chose"), string_computer,("so unfortuantely you lost."))
    rps()
elif answer == 1 and computer == 3:
    print(("The computer chose"), string_computer,("so you won! Congratulations!"))
    rps()
elif answer == 2 and computer == 1:
    print(("The computer chose"), string_computer,("so you won! Congratulations!"))
    rps()
elif answer == 2 and computer == 3:
    print(("The computer chose"), string_computer,("so unfortuantely you lost."))
    rps()
elif answer == 3 and computer == 1:
    print(("The computer chose"), string_computer,("so unfortuantely you lost."))
    rps()
else:
    print(("The computer chose"), string_computer,("so you won! Congratulations!"))
    rps()

`

当我尝试运行代码时,所有语法都是正确的,但它出现了“一定有一个小故障”,我将其添加进去以查看它是否没有选择 1 到 3 之间的数字。我该如何修复所以它会选择 1 到 3 之间的数字?

最佳答案

import random

computer = random.randint(1,3)

这里不需要 lambda 函数。

将 lambda 函数集 computer 包含为将生成 1 到 3 之间的随机数的函数:

>>> computer = lambda: random.randint(1, 3)
>>> computer
<function <lambda> at 0x000001F4DD2738C8>

如果您随后调用 computer(),您将获得一个 1 到 3 之间的随机数:

>>> computer()
2
>>> computer()
2
>>> computer()
1

对于您的功能来说,摆脱lambda:是最好的解决办法。如果您想在 if computer... 语句中添加括号,则可能会出现 glitch 语句,因为您将为每个生成一个新的随机 int computer() 调用。

关于python - 如何在 Python 3 中将变量设置为随机整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045869/

相关文章:

python - 将 JSON 发布到 Flask 会导致 400 Bad Request 错误

python - 如何从图中隔 ionic 网,包括深度为 n 的节点和边?

python - plotly : plotly 表达 add_vrect 到图的问题

python - 无法在 python 中使用 Chromedriver 和 selenium 消除音频错误

python - 根据列找出数据框中的缺失值

python - datetime.strptime 在 PyQt4 QtGui.QWidget 继承类中不起作用

python - 异步 DNS 解析器测试

python - 如何使用 Python 定义 : include letters and () but not include . 等正则表达式和数字

python - 如何在 Django Rest Framework 中通过电子邮件发送动态数据

python - 如何访问对列表中对的每个元素?