我的变量不会改变为玩家的偏好

时间:2018-01-25 20:59:45

标签: python python-3.x

我刚刚开始尝试通过编写这个简单的“游戏”来重新编写python中的编码,但我无法得到nrange和unumber等于玩家的偏好。

这是我到目前为止编写的代码,

import random
import time

nrange = 10
rnumber = random.randint(1, nrange)
unumber = 1

def start():
    nrange = input("How many numbers do you want to guess between? ")
    unumber = input("What will your number guess be? ")
    main()

def main():
    print ("Number Reveal in...")
    time.sleep(1)
    print ("3")
    time.sleep(1)
    print ("2")
    time.sleep(1)
    print ("1")
    time.sleep(1)
    nreveal()

def nreveal():
    if rnumber == unumber:
        print("The Number was ", rnumber, " Well done you guessed correctly",)
        tryagain = input("Do you wanna play again? (Y/N)")
        if tryagain == ("Y"):
            start()
        if tryagain == ("N"):
            print ("Ok, hope you enjoyed playing")
            time.sleep(2)
            quit()
    if rnumber != unumber:
        print("The Number was ", rnumber, " sorry but you guessed wrong",)
        tryagain = input("Do you wanna try again? (Y/N)")
        if tryagain == ("Y"):
            start()
        if tryagain == ("N"):
            print ("Ok, hope you enjoyed playing")
            time.sleep(2)
            quit()

start()

2 个答案:

答案 0 :(得分:0)

因为您在nrange中分配了unumberstart(),所以它们是该函数的局部变量,并且您在其他地方看不到对它们所做的更改。要修改全局变量,只需在start()

中将它们声明为全局变量
def start():
     global nrange, unumber
     # rest of code as you have it

答案 1 :(得分:0)

您的代码有三个问题:

  • 您只生成一次随机数
  • 您没有更新global
  • 中的start个变量
  • 您需要将输入的数字转换为ints

第一点应该是相当自我解释的(rnumber仅在代码主体中设置并且从未修改过),第二个问题可以通过以下代码片段看到:

>>> a = 5
>>> def b():
...     a = 6
... 
>>> b()
>>> a
5
>>> def c():
...     global a
...     a = 6
... 
>>> c()
>>> a
6

因此,如果...部分与您的问题相同,则以下内容现在可以正常运行:

import random
import time

rnumber, unumber = 0, 0

def start():
    global rnumber, unumber
    nrange = int(input("How many numbers do you want to guess between? "))
    unumber = int(input("What will your number guess be? "))
    rnumber = random.randint(1, nrange)
    main()

 ...

确实如此!这是我的测试运行:

How many numbers do you want to guess between? 100
What will your number guess be? 4
Number Reveal in...
3
2
1
The Number was  37  sorry but you guessed wrong
Do you wanna try again? (Y/N)Y
How many numbers do you want to guess between? 1
What will your number guess be? 1
Number Reveal in...
3
2
1
The Number was  1  Well done you guessed correctly
Do you wanna play again? (Y/N)N
Ok, hope you enjoyed playing