Shubham Srivastava Shubham Srivastava - 17 days ago 5
Python Question

How to Replace whitespace in a string in python when if condition is applied

I am applying this code. but it returns an exception on some test cases but other test cases it will return TRUE.

CASE 1:

sample input:

<br>source = 'Delhi'<br>
destination = 'Agra'<br>
Type = 'one-way'


Expected output:

if exist -> return 'already exist' else: insert into dB.


My output:
working correct

CASE 2:

Sample Input:


source = 'Delhi'<br>
destination = 'A gra'<br>
Type = 'one-way'<br>


Expected output:

if exist -> return 'already exist' else: insert into dB.


My output:
THROWING EXCEPTION

Error: local variable 'source' referenced before assignment

If I assign the variable as None. Then It will show success which is incorrect.

res = db.test("select source,destination,type from cities where source = '"+str(self.source)+"' and destination='"+str(self.destination)+"' and type = '"+str(self.type)+"'")
for row in res:
source = row['source']
destination = row['destination']
types = row['type']
src = self.source
dst = self.destination
typ = self.type
if str(src).replace(' ','').lower() == str(source).replace(' ','').lower() and str(dst).replace(' ','').lower() == str(destination).replace(' ','').lower() and str(typ).replace(' ','').lower() == str(types).replace(' ','').lower():
return "already exist"

Answer

Initialize source,destination and type variable outside the loop to empty string. You are trying to use a variable "source" which is initialized and then declared in for loop. You must initialize it outside the loop.

If you initialize only "source" outside, you would get the second exception as "local variable 'destination' referenced before assignment."

source = ""
destination = ""
types = ""
res = db.test("select source,destination,type from cities where source = '"+str(self.source)+"' and destination='"+str(self.destination)+"' and type = '"+str(self.type)+"'")
for row in res:
    source = row['source']
    destination = row['destination']
    types = row['type']
src = self.source
dst = self.destination
typ = self.type
if str(src).replace(' ','').lower() == str(source).replace(' ','').lower() and str(dst).replace(' ','').lower() == str(destination).replace(' ','').lower() and str(typ).replace(' ','').lower() == str(types).replace(' ','').lower():
     return "already exist"
Comments