重点是猜测从整数区间中选择的随机数,并在固定的尝试次数内进行。
main函数询问间隔的上限和用户可以给出的猜测数量。 然后核心函数应返回猜测值,因此当数字正确时,函数应立即终止。
我在调试时输入了一些print语句,我理解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 yThe point is to guess a random number choosen from an interval of integers and do it within a fixed numbers of attempts.
The main function asks the upper limit of the interval and the number of guesses the user can give. The core function then should return the guessed value so when the number is right the function should terminate immediately.
I put some print statement while debugging and I understood that the y value is not returned to the while statement from the core function.
# -*- 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最满意答案
您希望将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 。
You want to assign the return value of core back to the local y variable, it's not passed by reference:
y = core(x)You'll also need to set y before you go into the loop. Local variables in functions are not available in other functions.
As a result, you don't need to pass y to core(x) at all:
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 yand the loop becomes:
y = None while (x != y) and (i < t): y = core(x) i += 1It doesn't much matter what you set y to in the main() function to start with, as long as it'll never be equal to x before the user has made a guess.
更多推荐
发布评论