Shubham Srivastava Shubham Srivastava - 14 days ago 5
Python Question

How to replace whitespace in a string when a condition is applied

My code returns an exception on some test cases and TRUE on other test cases.

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 correctly

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:

Error: local variable 'source' referenced before assignment


If I assign the variable as
None
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