-1

I am making a python code to check if chaddar equal 1 and 'yes' in horn. However I cannot get the chaddar number from def sth(chaddar) and my code always print error. I cannot use golbal variable I can only use local variable.So I really need some help. Thanks

Here is my code:

def sth(chaddar):
  chaddar = 1 
def basic(chaddar):
  horn = input("answer: ")
  if chaddar ==1 and "yes" in horn:
    print("ok")
  else:
    print("error")
sth('chaddar')
basic('chaddar')

My Terminal:

answer: yes
 error
Tom
  • 21
  • 5

2 Answers2

0

This is all looking pretty crazy, but this should do it:

def basic(chaddar):
  horn = input("answer: ")
  if chaddar ==1 and "yes" in horn:
    print("ok")
  else:
    print("error")

basic(1)

Problems

  • The sth function is irrelevant

  • You were sending a string to basic but testing the value against 1.

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
0

sth("chaddar") doesn't set the local variable chaddar in basic() to 1; it only sets chaddar to be 1 in sth().

If you want to achieve this, then you would need to do:

def sth(chaddar):
  global chaddar
  chaddar = 1

def basic(chaddar):
  horn = input("answer: ")
  if chaddar == 1 and "yes" in horn:
    print("ok")
  else:
    print("error")

chaddar = "chaddar"
sth(chaddar)
basic(chaddar)

But this would violate your 'no globals' principal.

Or something like:

def sth(chaddarPath):
  with open(chaddarPath, "w") as chaddar:
  chaddar = 1 

def basic(chaddarPath):
  chaddarFile = open(chaddarPath, "r")
  chaddar = int(chaddarFile.read())
  chaddarFile.close()

  horn = input("answer: ")
  
  if chaddar == 1 and "yes" in horn:
    print("ok")
  else:
    print("error")

sth("chaddar.txt")
basic("chaddar.txt")

But this would be clunky and not very efficient.

sbottingota
  • 533
  • 1
  • 3
  • 18