2016-11-17 8 views
0

私のコードはいくつかのテストケースで例外を返し、他のテストケースではTRUEを返します。条件が適用されたときに文字列の空白を置き換える方法

CASE 1:

サンプル入力:

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

予想される出力:

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

マイ出力:

正しく

作業

CASE 2:

サンプル入力:

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

予想される出力:

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

マイ出力:

Error: local variable 'source' referenced before assignment 

私はNoneとして変数を割り当てた場合、それは意志成功していることを示すect。

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" 
+0

どの例外がありますか?あなたが私たちに何の情報も与えないときに、あなたが私たちにあなたを助けることを期待する方法 –

+0

私たちに完全な痕跡を見せてください。あなたの押し込みは正しいのですか? forループは3行しか含まないのでしょうか? –

+0

あなたが** sample Input **と呼んだのは 'res'の値ですか?そうでなければそれを提供できますか?あなたのコードはクラスの一部です。投稿する前にクラス外でテストしましたか?あなたは出力と**種類の**入力を提供しました(もし 'res'が入力なら辞書、リスト、リストの辞書?文字列?...)。エラーと適切なコードを使用して作業する... –

答えて

0

ループ外の変数をソース、宛先、およびタイプ変数を空の文字列に初期化します。 初期化され、forループで宣言された変数 "source"を使用しようとしています。ループの外側で初期化する必要があります。

「ソース」のみを外部に初期化すると、割り当て前に参照される「ローカル変数の宛先」として2番目の例外が発生します。

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" 
+0

** Thankz ** sir :) –

0

他にも、stacktraceを使って投稿を更新してください。そうでない場合は、エラーを読んでみてください。クエリを生成中であるとしているのはなぜ

  • (SQLインジェクションについての記事を読む)代わりにクエリパラメータを使用しますが、ユーザーの入力を使用している2つの観測、

    1. コードでエラーを発見することができませんでしたが、各変数を "str"に変換していますか?デフォルトでは "str"にする必要があります

    私はこれをコメントとして追加したいと思いますが、コメントを追加するには回答がありません。

  • +0

    エラー:割り当て前にローカル変数 'source'が参照されました 変数をNoneに割り当てると、その後、それは間違っている成功を示します。 –

    +0

    私は "str"を置いています。なぜなら、この特定のコードに対してpycharmをコーディングすると、strなしでreplace()が表示されないからです。どうしてか分かりません。 –

    +0

    Pythonはダックタイピングなので、コードが実行されたときに置き換えられます。pycharmはself.sourceなどの型を推論できないため表示されません... tyoe str。 .. isinstance(str、) –

    関連する問題