我是python的新手,正在尝试为类运行一些代码,但是我遇到了一个奇怪的错误提示,我只是为n和k设置了一个随机值,以查看代码是否可以工作
$python main.py
Traceback (most recent call last):
File "main.py", line 10, in <module>
while(k):
NameError: name 'k' is not defined
这是我的代码,我定义了n和n都没有问题,但是k似乎是一个问题
def binary(n,k):
n = 6
k = 1.5
#'n' is the fractional number
#'k' is the number of bits up to the loop ;
integral = int(n)
fraction = n-integral
b = '.'
while(k):
fraction = fraction * 2
fra_num = int(fraction)
if (frac_num == 1):
fraction = fraction - frac_num
b = b + '1'
else:
b = b + '0'
k = k - 1
print b
如所评论,您最大的问题是缩进。 while循环不在函数内部。尝试缩进:
def binary(n,k):
n = 6
k = 1.5
#'n' is the fractional number
#'k' is the number of bits up to the loop ;
integral = int(n)
fraction = n-integral
b = '.'
while(k):
fraction = fraction * 2
fra_num = int(fraction)
if (frac_num == 1):
fraction = fraction - frac_num
b = b + '1'
else:
b = b + '0'
k = k - 1
print b