为什么我会收到“未定义变量”?

时间:2019-09-08 13:09:22

标签: python python-3.x

我是Python的新手,希望能对此问题有所帮助。我遇到Undefined Variable 'r'错误,我有点迷失了解决方法。

尝试将'r变量定义为int,但不起作用

#!/usr/bin/env python3
def Checkdiv(n, d):
    r =int(n % d)
    if r==0:
        return (True,r)
    else:
        return (False,r)
n= int(input('Please enter the number to evaluate:'))
d= int(input('Please enter the divisor: '))

if Checkdiv(n,d) is True :
    print(f'{n} can be divided by {d} since the end remainder is {r}')
else: 
    print (f'{n} cannot be divided by {d} since remainder is {r}')

7 个答案:

答案 0 :(得分:1)

编辑:在OP编辑后答案变得无用

您尝试使用参数n和d调用该函数。您需要在调用函数之前分配它们或直接输入两个数字。 例如:

n = 6
d = 2
if Checkdiv(n,d) is True:
   pass

if Checkdiv(6,2) is True:
   pass

我希望这会有所帮助。

答案 1 :(得分:0)

只需简单地在函数中定义r,然后在打印中尝试使用Checkdiv中仅局部可见的r。您必须先写入Checkdiv的可变结果,然后在打印功能中使用它。

def Checkdiv(n, d):
    r =int(n % d)
    if r==0:
        return True
    else:
        return False
    n= int(input('Please enter the number to evaluate:'))
    d= int(input('Please enter the divisor: '))
n = 6
d = 2
r = Checkdiv(n,d)
if r:
   print(f'{n} can be divided by {d} since the end remainder is {r}')
else:
   print (f'{n} cannot be divided by {d} since remainder is {r}')

答案 2 :(得分:0)

变量“ r”仅存在于Checkdiv函数中,但您在函数外部对其进行了引用:

print(f'{n} can be divided by {d} since the end remainder is {r}')

答案 3 :(得分:0)

在Checkdiv函数之外定义r,并在函数中将r变量用作带有global关键字的全局变量;全局r,然后r = int(n%d)。这样其他代码块也可以看到r变量。

r = 0
def Checkdiv(n, d):
    global r
    r = int(n % d)
    if r==0:
        return True
    else:
        return False
n= int(input('Please enter the number to evaluate:'))
d= int(input('Please enter the divisor: '))


if Checkdiv(n,d) is True :
    print(f'{n} can be divided by {d} since the end remainder is {r}')
else: 
    print (f'{n} cannot be divided by {d} since remainder is {r}')

答案 4 :(得分:0)

编写代码的更好方法是

NaN

答案 5 :(得分:0)

我认为您使问题复杂化了。 这是一个简单的代码,它可以完成您想做的事情:

def check_div(n,d):
    r = n % d
    if r == 0:
        print('{} can be divided by {} since the end remainder is {}'.format(n ,d, r))
    else:
        print('{} cannot be divided by {} since remainder is {}'.format(n, d, r))

n= int(input('Please enter the number to evaluate:'))
d= int(input('Please enter the divisor: '))

check_div(n, d)

应在函数外部定义r的代码问题。

答案 6 :(得分:0)

我相信您在值的生命周期上遇到麻烦,在函数内部声明的变量(除非与global关键字一起使用)在函数返回时停止引用,因此被垃圾收集器删除。

但是在您的代码中您返回r,那么为什么它不起作用? 好吧,你返回一个元组(布尔值,整数)。

做事的时候

if Checkdiv(n,d):

您将评估元组是否为空,而不是布尔值。 并且由于未分配返回值而导致返回值丢失。

您可以将代码分解为具有这些值(可以检查python unpack)

boolean, r = Checkdiv(n,d)
# now you can test and use the return value,
相关问题