python - 在 Mastermind 游戏中重复功能的问题
问题描述
我正在设计一个用 python 玩的策划游戏。但是当我尝试设置一个函数以在尝试不完全正确时重复自身时遇到一些问题。
我的代码分为两部分。对于第一部分,它要求用户输入正确的号码,然后第二个用户尝试输入他的尝试号码。代码的第二部分将他的尝试分解为数字列表,并计算正确整数的数量和正确位置的整数数量,然后如果答案不完全正确,程序会要求用户进行第二次输入。
def getnumber():
predestine = input("Please input your test number")
a = str(predestine)
attempt()
def attempt():
attempt = input("Attempt:")
b = str(attempt)
correctrecord = []
sequencerecord = []
for i in b:
if i in a:
correctrecord.append(1)
for i in range(0,4):
if b[i] == a[i]:
s equencerecord.append(1)
correctlength = len(correctrecord)
sequencelength = len(sequencerecord)
print(f"You have made {correctlength} correct attempts, and of these {sequencelength} are of correct positions")
if sequencelength == 4:
print("You have won, the game is ended")
else:
return attempt()
问题在于最后一个代码:返回尝试()。似乎无法使用“str object not callable”错误重复该函数。
解决方案
您的代码中的问题在于变量阴影。
您的重复函数位于名为 的变量中attempt
,即全局变量。然后,在attempt
函数内部定义一个attempt
字符串变量,该变量是该函数的本地变量,因此暂时隐藏了attempt
保存该函数的全局变量。
因此,调用attempt()
失败,因为您实际上是在尝试调用字符串。
解决方案是重命名本地字符串变量attempt
以不影响全局变量:
def attempt():
attempt_ = input("Attempt:")
b = str(attempt_)
correctrecord = []
sequencerecord = []
for i in b:
if i in a:
correctrecord.append(1)
for i in range(0,4):
if b[i] == a[i]:
sequencerecord.append(1)
correctlength = len(correctrecord)
sequencelength = len(sequencerecord)
print(f"You have made {correctlength} correct attempts, and of these {sequencelength} are of correct positions")
if sequencelength == 4:
print("You have won, the game is ended")
else:
return attempt()
推荐阅读
- html - 我在更改导航中导航链接的文本颜色时遇到问题。任何帮助,将不胜感激
- java - 在链接表 postgresql 中创建行
- python - 格式化 URL 的正确 python/django 方式是什么?
- html - 填充最后一个块的空闲空间
- javascript - 迭代深度嵌套的 JSON
- scala - ZIO Streams:ZSink 和 ZTransducer 有什么区别?
- go - 数学/大:常量 18446744073709551616 溢出 int?
- python - Python Django Post 请求垃圾邮件预防
- glsl - 不正常处理obj文件
- python -
, ValueError("could not convert string to float: 'X'"),