<p>您可以多次使用相同的变量名。Python函数是一级公民,它允许您执行以下操作:</p>
<pre><code># define a function by name r
def r():
return 1
print(type(r)) # <class 'function'> now r is a function
# reassign name r to be a string
r = "22"
print(type(r)) # <class 'str'> now r is a string
</code></pre>
<p>如果你做了<code>r()</code>,现在你得到了<code>TypeError: 'str' object is not callable</code></p>
<hr/>
<p>您的代码使用全局变量,然后再次调用自己的函数,这可能导致递归溢出—请参见<a href="https://stackoverflow.com/questions/3323001/what-is-the-maximum-recursion-depth-in-python-and-how-to-increase-it">What is the maximum recursion depth in Python, and how to increase it?</a></p>
<p>当存在重复项时,计算正确“位数”的数量时,您将得到错误的结果-请尝试使用“1122”作为正确值,使用“1234”作为尝试值。你知道吗</p>
<p>递归是不需要你的游戏代码。我对它进行了一些调整,以展示一种不同的方式:</p>
<pre><code>def getnumber(text):
"""Loops until a number is inputted. Returns the number as string.
'text' is the prompt for the user when asking for a number."""
while True:
try:
predestine = int(input(text).strip())
return str(predestine)
except:
print("Only numbers allowed!")
def attempt(correct_number):
"""One game round, returns True if correct result was found."""
attempt = getnumber("Attempt: ")
# avoid double-counting for f.e. 1212 and 1111 inputs
correct_digits = len(set(attempt) & set(correct_number))
sequencelength = 0 # no need to collect into list and use len
for i,c in enumerate(attempt): # simply increment directly
if c == correct_number[i]:
sequencelength += 1
print(f"You have found {correct_digits} correct digits, and of these {sequencelength} are of correct positions.")
if len(attempt) < len(correct_number):
print("Your number has too few digits.")
elif len(attempt) > len(correct_number):
print("Your number has too many digits.")
return correct_number == attempt
# game - first get the correct number
number = getnumber("Please input your test number: ")
# loop until the attempt() returns True
ok = False
while not ok:
ok = attempt(number)
print("You have won, the game is ended")
</code></pre>
<p>输出:</p>
<pre><code>Please input your test number: 1234
Attempt: 1111
You have found 1 correct digits, and of these 1 are of correct positions.
Attempt: 1212
You have found 2 correct digits, and of these 2 are of correct positions.
Attempt: 1321
You have found 3 correct digits, and of these 1 are of correct positions.
Attempt: 1234
You have found 4 correct digits, and of these 4 are of correct positions.
You have won, the game is ended
</code></pre>