没有局部变量,但警告:在分配之前引用

时间:2017-06-22 13:47:37

标签: python python-3.x pycharm local-variables

我使用PyCharm社区编辑器进行了简单的练习,并收到警告:

  

此检查会警告之前引用的局部变量   分配

但是这里没有局部变量,并且它在Windows PowerShell上运行良好。它有什么问题?

for(int row = start.Row; row <= end.Row; row++)
{
    SqlCommand cmd = new SqlCommand("GetKeyNumber", homelinkconn);
    cmd.CommandType= CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@KeyName", "VGMNO");
    cmd.Parameters.AddWithValue("@KeyNo", SqlDbType.Int);

    var returnParameter = cmd.Parameters.Add("@KeyNo", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    cmd.ExecuteNonQuery();

    var key = returnParameter.Value;
    dt.Rows[dt.Rows.Count-1]["VGMNO"] = key;
}

同样,这里的修订版仍然存在同样的问题。

# This is a guess the number game.
import random
secret_number = random.randint(1, 21)
print("I am thinking of a number between 1 and 20. You have three chances.")

# Ask the player to guess 3 times.
for guesses_taken in range(1, 4):
    guess = int(input('Take a guess.\n'))
    if guess > secret_number:
        print('Your guess is too high.')
    elif guess < secret_number:
        print('Your guess is to low.')
    elif guess == secret_number:
        if guesses_taken == 1:
            print('Oh my god. You just guessed only one time.')
        else:
            print("You are right. I'm thinking of %s, and you guessed my 
                number in %s guesses." % (secret_number, guesses_taken))
    else:
        break
if guess != secret_number:  --> # Name 'guess' can be not defined.
    print('Nope. The number I was thinking of was ' + str(secret_number) + '.')

1 个答案:

答案 0 :(得分:2)

您收到警告:他们并不意味着您的代码无法按预期工作,但他们的意思是告诉您可能出错在某些情况下。

我没有使用PyCharm,但我看到这些警告的原因是:

  • guessfor循环中分配。因此,如果循环至少执行一次,则永远不会分配guess

  • guesses_taken将首先分配range的第一个值,然后是第二个......但是如果range是空的,它也永远不会获得分配

例如见:

for loop_index in range(1, -1):  # empty! 
    my_value_assigned_in_loop = 1

print(loop_index)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-31-39f9878362fc> in <module>()
      2     my_value_assigned_in_loop = 1
      3 
----> 4 print(loop_index)

NameError: name 'loop_index' is not defined