Name error: name 'variable' is not defined

Asked

Viewed 203 times

0

In the second part, when printing 'Perd', the error "Name error: name 'Perd' is not defined" appears, as I correct?

first part

def test(usr,val):
  perd = 0
  win = 0
  if usr.upper() == 'A':
    print('SOMA = ',val)
    if val == 21:
      win == 1
    if val > 21:
      perd == 1
  else:
    if val == 21:
      perd == 1

2nd part

print("---------",perd)
  • Part two, is it outside the test function? If it is, the variable will really not exist.

1 answer

0

Hello alive without realizing what this code is for, I can correct what is wrong.... first you cannot access the variable Perd because it is in the Scope of a function, ie will be used at the time of execution of this and later will be removed from memory with GC, however a way to access the values of the function I leave below how to do, returning what it loads to the variable.

NOTE: Warning for a common error, was assigning values to variables with double equal, so Perd == 1, so you will never receive the value but compare and can return a boleane, (if you had a Return) if the Perd variable that was initialized to zero is equal to 1, soon returns a False, the assignment should be Perd = 1. I hope I’ve made it clear what you were doing wrong and why.

Solution

def test(usr,val):
  perd = 0
  win = 0
  if usr.upper() == 'A':
    print('SOMA = ',val)
    if val == 21:
      win = 1
    if val > 21:
      perd = 1
    return perd
  else:
    if val == 21:
      perd = 1
    return perd

print(test('A', 221))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.