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的值?
答案 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