python - Python,函数没有被随机调用
问题描述
我已经完成了石头剪刀布或纸质程序的编写。我有一个函数 ai() 可以随机决定计算机端。此函数还打印每次循环完成时我调用的计算机的决定,但是,有时它只是不这样做。你能帮我弄清楚为什么吗?任何改进建议都非常受欢迎
这是我的功能
def ai():
number = random.randint(1,4)
if number == 1:
global aiinput
aiinput = ("rock")
print(("The choice of computer is: "),aiinput)
elif number == 2:
aiinput = ("paper")
print(("The choice of computer is: "),aiinput)
elif number == 3:
aiinput = ("scissors")
print(("The choice of computer is: "),aiinput)
这是我剩下的代码
import random
def ai():
number = random.randint(1,4)
if number == 1:
global aiinput
aiinput = ("rock")
print(("The choice of computer is: "),aiinput)
elif number == 2:
aiinput = ("paper")
print(("The choice of computer is: "),aiinput)
elif number == 3:
aiinput = ("scissors")
print(("The choice of computer is: "),aiinput)
def draw():
print ("Draw")
def loser():
print ("Loser!")
def winner():
print ("You won!")
print("Welcome to the game to quit prompt q")
while True:
usrinp = input("rock, scissors or paper? you can also prompt r,s or p: ")
ai()
if usrinp == ("r") and aiinput == ("rock"):
draw()
elif usrinp == ("r") and aiinput == ("paper"):
loser()
elif usrinp == ("r") and aiinput == ("scissors"):
winner()
if usrinp == ("p") and aiinput == ("rock"):
winner()
elif usrinp == ("p") and aiinput == ("paper"):
draw()
elif usrinp == ("p") and aiinput == ("scissors"):
loser()
if usrinp == ("s") and aiinput == ("rock"):
loser()
elif usrinp == ("s") and aiinput == ("paper"):
winner()
elif usrinp == ("s") and aiinput == ("scissors"):
draw()
if usrinp == ("q"):
quit()
在这里你可以看到调试 调试结果
解决方案
您只需在函数中设置global aiinput
a 。在ifs之前做。您还需要使用.if
ai
randint(1, 3)
def ai():
global aiinput # This goes before the conditions.
aiinput = {1: "rock",
2: "paper",
3: "scissors"}[random.randint(1, 3)]
print("The choice of computer is: ", aiinput)
推荐阅读
- wordpress - 如何更改 WordPress 以使用 Intranet 中的头像?
- javascript - 动态数组元素的求值顺序是否有保证?
- python - 我如何锁定提到的频道?不和谐.py
- python-3.x - argparser.ArgumentParser 在 python 2.7 和 python 3.6 之间变化?
- azure - JSON解析日志条目
- angular - 原理图工作流失败
- javascript - 为什么我的 json.dumps 没有将报价值转换为我的浏览器?
- regex - 在谷歌表格中运行用于条件格式的自定义公式仅格式化“应用于范围”中的第一个单元格
- unity3d - UNITY2D:在具有相同标签和相同图层的两个对象之间进行选择
- ios - 在 iOS 上通过 Spotify App Remote 的 SPTSession 进行身份验证时获取一个奇怪的刷新令牌