为什么我没有在这个高低代码中得到游戏结束的消息


import random
game = False
random_num = random.randint(1 , 100)
print(random_num)
x = 0
if x == 1:
game = True
def code():
if number == random_num :
x + 1
print('you von')
elif number > random_num :
print('lov')
elif number < random_num :
print('higher')
if game == True:
print ("game over")
while x == 0:
number = int(input("Guess the number "))
code()

如果猜测到正确的数字,代码应该结束游戏结束从未打印一直让我猜的数字

我也试过这个代码,它一直失败pycharm灰显->游戏in if函数game=真正的

import random
game = False
random_num = random.randint(1 , 100)
print(random_num)
#x = 0
#if x == 1:
#game = True
def code():
if number == random_num :
game = True
print('you von')
elif number > random_num :
print('lov')
elif number < random_num :
print('higher')
if game == True:
print ("game over")
while game == False:
number = int(input("Guess the number "))
code()

这是因为您正在尝试更改game变量,它是global变量。它位于code函数的范围之外。

为了实现您想要的,您必须在code()函数的开头将game声明为全局。否则,它将game作为新的局部变量:

def code():
global game
[...]

我发现了一个你可能会觉得有用的相关问题:Python函数全局变量?

来自python编程常见问题解答:

在Python中,仅在函数内部引用的变量是隐式全局的。如果变量在函数体中的任何位置都被赋值,则除非明确声明为全局,否则它将被假定为局部变量。

因此,这里有几件事,但最重要的是,如果我们猜测正确,变量x不会返回新值。为了从具有更新变量的函数中返回变量,需要返回变量,如下所示:

def code(x):
if number == random_num :
x = 1
print('you von')
elif number > random_num :
print('lov')
elif number < random_num :
print('higher')
return x
while x == 0:
number = int(input("Guess the number "))
x = code(x)
print(x)

语句的顺序也意味着其中一些语句将被跳过。当我们这样重新订购时:

import random
game = False
random_num = random.randint(1 , 100)
print(random_num)
x = 0
def code(x,number):
if number == random_num :
x = 1
print('you von')
elif number > random_num :
print('lov')
elif number < random_num :
print('higher')
return x
while x == 0:
number = int(input("Guess the number "))
x = code(x,number)
print(x)
if x == 1:
game = True
if game == True:
print ("game over")

我们得到所需的输出,当猜到数字时,程序退出。

最新更新