作为我对Python研究的一部分,我编写了这个小的随机数猜测游戏。我的问题是,如果我单独返回一个函数,会发生什么?这是否被视为良好做法?这是否会导致某种缓冲区或堆栈溢出?(没有双关语)
我真的没有找到一个明确的答案,甚至对其他语言也没有
如果有人想问为什么,我这样做是因为我想循环程序,直到用户输入“exit”
# Simple guess the random number game
# Import this module for generating a random number
import random
# Function to determine if answer is too low, too high, or if it is correct
def guessFunc(guessInput, randomNum):
if guessInput < randomNum:
return 'The number is too low'
elif guessInput > randomNum:
return 'The number is too high.'
else:
return 'Correct!'
# Function that checks if user input is valid.
def checkValid_Input(userInput):
if userInput.isdigit():
return True
return False
# The "main" function of the whole game
def mainFunc():
userGuess = ''
guessResult = ''
secretNum = random.randint(0, 20) #Generate random number
tries = 0
# Game loop, the program ends if user types 'Exit'/'exit'.
while True:
print('I\'m thinking of a number between 0 and 20...')
userGuess = input()
# Check first if user typed 'exit'. If true, terminates the program
# if False, continues code execution.
if str.lower(userGuess) == 'exit':
return
# If the previous condition is false, perform this method.
# This checks if user input is valid.
isValid = checkValid_Input(userGuess)
if isValid == False:
print('Invalid input, please try again.\n')
else:
guessResult = guessFunc(int(userGuess), secretNum)
tries = tries + 1
print(guessResult + '\n')
if tries == 6 and guessResult != 'Correct!':
print('Nope, the secret number is: ' + str(secretNum))
print('Press any key to continue')
_ = input()
return mainFunc()
if tries <=6 and guessResult == 'Correct!':
print('It took you ' + str(tries) + ' tries to get it.')
print('Press any key to continue')
_ = input()
return mainFunc()
# Initialize/call main function
mainFunc()
为了稍微澄清一下,我将这个问题简化到了获得一些输出和回溯所需的最低限度。我把代码放在了
test1.py
请注意,
mainFunc()
中的任何内容都不会导致导致最终退出条件的逐渐变化,因此它所做的只是增加一个计数器,并在到达返回语句之前打印新值:这导致Python执行1012条print语句,生成以下(高度缩写)输出:
…在这一点上,它通过以下回溯失败:
这是有意义的,因为每次到达
return mainFunc()
语句时,它都会调用mainFunc()
,以确定返回给调用方的值(第一次调用时隐式地返回__main()__
,之后递归地返回mainFunc()
)回溯支持我们的普遍共识,即它确实是递归,并且递归确实有(默认)限制
最后,要回答问题
is this good practice?
:有时是,有时不是-我可以想到一个非常适合递归设计的常见应用程序:
阶乘,其中
factorial(n)
应返回3x2x1=6
计算的输出,其中n=3
。退出条件是,每个后续调用调用阶乘(n-1),因此传递的参数在函数中逐渐向退出条件递减为了递归,必须有一个退出条件,否则无止境循环最终将导致
RecursionError
相关问题 更多 >
编程相关推荐