为什么我不能在此代码中打印x的值?

时间:2020-07-16 14:47:21

标签: python-3.6

from os import urandom
from math import log

def urandint(a,b):
    x=urandom(int(log(b-a+1)/log(256))+ 1)
    total = 0
    for (i,y) in enumerate(x):
        total +=y*(2**i)
    return total%(b-a+1)+a

print(urandint(5,8))
print(x)

当我尝试打印x的值时,出现此错误:./ urandom_function.py

7
Traceback (most recent call last):
  File "./urandom_function.py", line 14, in <module>
    print(x)
NameError: name 'x' is not defined

我该如何纠正并打印x的值?

1 个答案:

答案 0 :(得分:0)

不是很精通我的编程,但是据我所知,因为“ x”是局部变量,因此无法从外部进行访问。尝试将'print(x)放入函数中。即

从操作系统导入urandom

从数学导入日志中

def urandint(a,b):

x = urandom(int(log(b-a+1)/log(256))+ 1)
print(x)
total = 0
for (i,y) in enumerate(x):
    total +=y*(2**i)
return total%(b-a+1)+a

print(urandint(5,8))

答案: b'\ xb6' 7