【问题标题】:Return a value from a function called in while loop从 while 循环中调用的函数返回一个值
【发布时间】:2013-01-26 16:49:25
【问题描述】:

关键是要从一个整数区间中猜测一个随机数,并在固定的尝试次数内进行。

main 函数询问区间的上限和用户可以给出的猜测次数。然后核心函数应该返回猜测的值,所以当数字正确时,函数应该立即终止。

我在调试时放了一些打印语句,我了解到y 值不会从core 函数返回到while 语句。

# -*- coding: utf-8 -*-
def main():
    from random import choice
    p = input("choose upper limit: ")
    t = input("how many attempts: ")
    pool = range(p+1)
    x = choice(pool)
    i = 1
    while ((x != y) and (i < t)):
        core(x,y)
        i += 1

def core(x,y):
    y = input("choose a number: ")
    if y == x:
        print("You gussed the right number!")
        return y
    elif y > x:
        print("The number is lower, try again")
        return y
    else:
        print("The number is higher, try again")
        return y

【问题讨论】:

    标签: function python-2.7 while-loop


    【解决方案1】:
    y = -1
    while ((x != y) and (i < t)):
        y = core(x,y)
        i += 1
    

    您在循环之前“初始化” y。在循环内部,您将 y 设置为 core() 函数的结果。

    【讨论】:

    • 非常感谢,我现在可以理解错误了。
    【解决方案2】:

    您想将core 的返回值分配回本地y 变量,它不是通过引用传递的:

    y = core(x)
    

    您还需要在进入循环之前设置y。函数中的局部变量在其他函数中不可用。

    因此,您根本不需要将y 传递给core(x)

    def core(x):
        y = input("choose a number: ")
        if y == x:
            print("You gussed the right number!")
            return y
        elif y > x:
            print("The number is lower, try again")
            return y
        else:
            print("The number is higher, try again")
            return y
    

    然后循环变成:

    y = None
    while (x != y) and (i < t):
        y = core(x)
        i += 1
    

    main() 函数中将y 设置为开始并不重要什么,只要在用户之前它永远不会等于x猜测了一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 2019-03-31
      • 2017-04-03
      • 1970-01-01
      • 2016-03-23
      • 2019-09-06
      • 2014-04-10
      相关资源
      最近更新 更多