Python 通过另一个函数访问一个函数的返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37088457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing returned values from a function, by another function
提问by KiliBio
I'm kinda new to programming in general, just started to really get into python. And I'm working on a number guesser project.
我对编程有点陌生,刚刚开始真正进入 python。我正在做一个数字猜测器项目。
import random
def main(): # main function
print("Welcome to the number guesser game")
range_func()
max_guess_number(lower_range_cut, upper_range_cut)
evaluation(random_number, total_guesses)
def range_func(): # allows user to select a range for the number guess
print("Please select a range in which you would like to guess.")
lower_range_cut = int(input("Lower boundary limit: "))
global lower_range_cut
upper_range_cut = int(input("Upper boundary limit: "))
global upper_range_cut
random_number = random.randint(lower_range_cut,upper_range_cut)
global random_number
return lower_range_cut, upper_range_cut, random_number
def max_guess_number(low,high): # returns the total number of guesses
total_numbers = (high - low) + 1
total_guesses = 0
while (2**total_guesses) < total_numbers:
total_guesses += 1
print ("You have a total of %d guesses\n"
"for your range between %d to %d"
% (total_guesses, low, high))
global total_guesses
return total_guesses
def evaluation(random_number, total_guesses): # evaluates the users input
guess_count = 0
while guess_count < total_guesses:
user_guess = int(input("Your guess: "))
print("Your guess is: %d" % (user_guess))
if (random_number == user_guess):
print("You got it ")
break
elif user_guess > random_number:
print("Guess lower!")
guess_count += 1
else:
print("Guess higher!")
guess_count += 1
if __name__ == "__main__":
main()
One problem I've experienced while writing that, is that I wasn't able to execute this program without redefining each variables as a global variable. Just by returning the values from one function, I was not able to access e.g. the second returned variable upper_range_cut from the range_function
我在编写该程序时遇到的一个问题是,如果不将每个变量重新定义为全局变量,我就无法执行该程序。仅通过从一个函数返回值,我无法访问例如从 range_function 返回的第二个变量 upper_range_cut
It there a way to handle that somehow shorter?
有没有办法以某种方式更短地处理它?
Also I'm happy about every note on the code itself (readability, function use, length). I know it could have made this code a lot shorter maybe by using list comprehension, but I don't really have the eye for seeing opportunities in this area yet.
此外,我对代码本身的每个注释(可读性、函数使用、长度)感到高兴。我知道它可以通过使用列表理解使这段代码更短,但我还没有真正看到这个领域的机会。
So thanks for any help!
所以感谢您的帮助!
KiliBio
奇力生物
采纳答案by misshapen
You're pretty much there. You can remove all globals, then just store the values returned from each function to local variables, and pass them in to new functions.
你几乎在那里。您可以删除所有全局变量,然后将每个函数返回的值存储到局部变量中,然后将它们传递给新函数。
The only other changes I've made below are:
我在下面所做的唯一其他更改是:
- Breaking out of the evaluation loop if the answer is guessed correctly.
- Printing a message if no guess is found in the given time. See: Else clause on Python while statement
- The bottom two lines allow the script to be run from the command line. See: What does if __name__ == "__main__": do?
- 如果正确猜出答案,则跳出评估循环。
- 如果在给定时间内没有找到猜测,则打印一条消息。请参阅:关于 Python while 语句的 Else 子句
- 底部两行允许从命令行运行脚本。请参阅:if __name__ == "__main__": do?
Otherwise you're looking good.
否则你看起来很好。
import random
def main(): # main function
print("Welcome to the number guesser game")
lower, upper, rand = range_func()
total_guesses = max_guess_number(lower, upper)
evaluation(rand, total_guesses)
def range_func(): # allows user to select a range for the number guess
print("Please select a range in which you would like to guess.")
lower_range_cut = int(input("Lower boundary limit: "))
upper_range_cut = int(input("Upper boundary limit: "))
random_number = random.randint(lower_range_cut, upper_range_cut)
return lower_range_cut, upper_range_cut, random_number
def max_guess_number(low,high): # returns the total number of guesses
total_numbers = (high - low) + 1
total_guesses = 0
while (2**total_guesses) < total_numbers:
total_guesses += 1
print ("You have a total of %d guesses\n"
"for your range between %d to %d"
% (total_guesses, low, high))
return total_guesses
def evaluation(random_number, total_guesses): # evaluates the users input
guess_count = 0
while guess_count < total_guesses:
guess_count += 1
user_guess = int(input("Your guess: "))
print("Your guess is: %d" % (user_guess))
if (random_number == user_guess):
print("You got it!")
break
else:
print "Sorry, you didn't guess it in time. The answer was: %d" % random_number
if __name__ == '__main__':
main()
回答by AKS
You don't need to define global
. You can just assign the values you are returning from a function to variable(s).
您不需要定义global
. 您可以将您从函数返回的值分配给变量。
A simple example:
一个简单的例子:
def add(a, b):
"""This function returns the sum of two numbers"""
return a + b
Now in your console, you could do following
现在在您的控制台中,您可以执行以下操作
# print the return
>>> print(add(2, 3))
5
# assign it to a variable
>>> c = add(2, 3)
>>> c
5
In your main
function you need to assign the values which are returned by different functions to variables which you can further pass to other functions.
在您的main
函数中,您需要将不同函数返回的值分配给您可以进一步传递给其他函数的变量。
def main(): # main function
print("Welcome to the number guesser game")
lower_range_cut, upper_range_cut, random_number = range_func()
total_guesses = max_guess_number(lower_range_cut, upper_range_cut)
evaluation(random_number, total_guesses)