multiple parameters in if statement

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kun

    #1

    multiple parameters in if statement

    I am trying to make an if-statement that will not do anything and print
    'nothing entered' if there is nothing entered in a form. I have the
    following code that does that, however, now even if I enter something
    into the form, the code still outputs 'nothing entered'. This violates
    the if statement and I am wondering what I did wrong.

    if form.has_key("d elete_id") and form["delete_id"].value != "" and
    form.has_key("d elete_date") and form["delete_dat e"].value != "" and
    form.has_key("d elete_purchaset ype") and
    form["delete_purchas etype"].value != "" and form.has_key("d elete_price")
    and form["delete_pri ce"].value != "" and form.has_key("d elete_comment")
    and form["delete_comment "].value != "":
    delete_id=form['delete_id'].value
    delete_date=for m['delete_date'].value
    delete_purchase type=form['delete_purchas etype'].value
    delete_price=fo rm['delete_price'].value
    delete_comment= form['delete_comment '].value
    else:
    print "ERROR: Nothing entered!"
    raise Exception

  • Steven D'Aprano

    #2
    Re: multiple parameters in if statement

    On Sat, 15 Apr 2006 20:28:47 -0400, Kun wrote:
    [color=blue]
    > I am trying to make an if-statement that will not do anything and print
    > 'nothing entered' if there is nothing entered in a form. I have the
    > following code that does that, however, now even if I enter something
    > into the form, the code still outputs 'nothing entered'. This violates
    > the if statement and I am wondering what I did wrong.
    >
    > if form.has_key("d elete_id") and form["delete_id"].value != "" and
    > form.has_key("d elete_date") and form["delete_dat e"].value != "" and
    > form.has_key("d elete_purchaset ype") and
    > form["delete_purchas etype"].value != "" and form.has_key("d elete_price")
    > and form["delete_pri ce"].value != "" and form.has_key("d elete_comment")
    > and form["delete_comment "].value != "":
    > delete_id=form['delete_id'].value
    > delete_date=for m['delete_date'].value
    > delete_purchase type=form['delete_purchas etype'].value
    > delete_price=fo rm['delete_price'].value
    > delete_comment= form['delete_comment '].value
    > else:
    > print "ERROR: Nothing entered!"
    > raise Exception[/color]


    That's rather, um, unfortunate looking code.

    Instead of making lots of tests like this:

    if form.has_key(ke y) and form[key].value != "" ...

    you might find it useful to create a helper function:

    def get(form, key):
    if form.has_key(ke y):
    return form[key].value
    else:
    return ""

    Now you don't need to test for existence and non-emptiness, because
    missing values will be empty. You just use it like this:

    if get(form, key) != "" and ...


    Using the get helper function, your test becomes much simpler:

    if get(form, "delete_id" ) != "" and get(form, "delete_dat e") != "" \
    and get(form, "delete_purchas etype") != "" and \
    get(form, "delete_pri ce") != "" and get(form, "delete_comment ") != "":
    do_something()
    else:
    raise ValueError("not hing entered")

    But that's still too complicated. In Python, every object can be
    tested by if...else directly. Strings are all True, except for the empty
    string, which is False.

    As an experiment, try this:

    if "something" :
    print "Something is not nothing."
    else:
    print "Empty string."

    if "":
    print "Something is not nothing"
    else:
    print "Empty string."


    So your if...else test becomes simpler:

    if get(form, "delete_id" ) and get(form, "delete_dat e") and \
    get(form, "delete_purchas etype") and get(form, "delete_pri ce") and \
    get(form, "delete_comment "):
    do_something()
    else:
    raise ValueError("not hing entered")


    Now your test checks that every field is non-empty, and if so, calls
    do_something(), otherwise it raises an error.

    But in fact, that gets the logic backwards. You want to raise an error
    only if every field is empty. So your test becomes:

    if get(form, "delete_id" ) or get(form, "delete_dat e") or \
    get(form, "delete_purchas etype") or get(form, "delete_pri ce") or \
    get(form, "delete_comment "):
    do_something()
    else:
    raise ValueError("not hing entered")




    --
    Steven.

    Comment

    • John Machin

      #3
      Re: multiple parameters in if statement

      On 16/04/2006 10:28 AM, Kun wrote:[color=blue]
      > I am trying to make an if-statement that will not do anything and print
      > 'nothing entered' if there is nothing entered in a form. I have the
      > following code that does that, however, now even if I enter something
      > into the form, the code still outputs 'nothing entered'. This violates
      > the if statement and I am wondering what I did wrong.
      >
      > if form.has_key("d elete_id") and form["delete_id"].value != "" and[/color]

      Unless your code needs to run on Python 2.1, consider using the <key> in
      <dict> construct instead of <dict>.has_key( <key>) -- it's not only less
      wear and tear on the the eyeballs and fingers, it's faster.

      Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32[color=blue][color=green][color=darkred]
      >>> foo = {}; foo['bar'] = 'zot'
      >>> foo.has_key('ba r')[/color][/color][/color]
      1[color=blue][color=green][color=darkred]
      >>> 'bar' in foo[/color][/color][/color]
      Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      TypeError: 'in' or 'not in' needs sequence right argument[color=blue][color=green][color=darkred]
      >>>[/color][/color][/color]

      Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32[color=blue][color=green][color=darkred]
      >>> foo = {}; foo['bar'] = 'zot'
      >>> foo.has_key('ba r')[/color][/color][/color]
      1[color=blue][color=green][color=darkred]
      >>> 'bar' in foo[/color][/color][/color]
      1[color=blue][color=green][color=darkred]
      >>>[/color][/color][/color]

      Comment

      • John Zenger

        #4
        Re: multiple parameters in if statement

        Try this:

        if form.get("delet e_id","") != "" and form.get("delet e_data","") != ""
        and...

        the "get" method lets you have an optional second argument that gets
        returned if the key is not in the dictionary.

        Also, am I reading your code right? If I enter some fields but not all,
        you print a message that says "Nothing entered." Nothing?

        The other thing I'd recommend is stick that long list of fields in a
        list, and then do operations on that list:

        fields = ['delete_id', 'delete_date', 'delete_purchas etype',
        'delete_price', 'delete_comment ']

        then to see if all those fields are empty:

        everything = ""
        for field in fields:
        everything += form.get(field, "")
        if everything == "":
        print "Absolutely nothing entered!"

        Kun wrote:[color=blue]
        > I am trying to make an if-statement that will not do anything and print
        > 'nothing entered' if there is nothing entered in a form. I have the
        > following code that does that, however, now even if I enter something
        > into the form, the code still outputs 'nothing entered'. This violates
        > the if statement and I am wondering what I did wrong.
        >
        > if form.has_key("d elete_id") and form["delete_id"].value != "" and
        > form.has_key("d elete_date") and form["delete_dat e"].value != "" and
        > form.has_key("d elete_purchaset ype") and
        > form["delete_purchas etype"].value != "" and form.has_key("d elete_price")
        > and form["delete_pri ce"].value != "" and form.has_key("d elete_comment")
        > and form["delete_comment "].value != "":
        > delete_id=form['delete_id'].value
        > delete_date=for m['delete_date'].value
        > delete_purchase type=form['delete_purchas etype'].value
        > delete_price=fo rm['delete_price'].value
        > delete_comment= form['delete_comment '].value
        > else:
        > print "ERROR: Nothing entered!"
        > raise Exception
        >[/color]

        Comment

        • John Machin

          #5
          Re: multiple parameters in if statement

          On 16/04/2006 1:43 PM, John Zenger wrote:[color=blue]
          >
          > The other thing I'd recommend is stick that long list of fields in a
          > list, and then do operations on that list:
          >
          > fields = ['delete_id', 'delete_date', 'delete_purchas etype',
          > 'delete_price', 'delete_comment ']
          >
          > then to see if all those fields are empty:
          >
          > everything = ""
          > for field in fields:
          > everything += form.get(field, "")[/color]

          Or everything = "".join(form.ge t(field, "") for field in fields)

          Somewhat labour-intensive. It appears from the OP's description that no
          other entries can exist in the dictionary. If this is so, then:

          everything = "".join(form.va lues())

          but what the user sees on screen isn't necessarily what you get, so:

          everything = "".join(form.va lues()).strip()
          [color=blue]
          > if everything == "":
          > print "Absolutely nothing entered!"
          >[/color]

          Comment

          • John Zenger

            #6
            Re: multiple parameters in if statement

            Yup, join is better. The problem with using form.values() is that it
            will break if the HTML changes and adds some sort of new field that this
            function does not care about, or if an attacker introduces bogus fields
            into his query.

            John Machin wrote:[color=blue]
            > On 16/04/2006 1:43 PM, John Zenger wrote:
            >[color=green]
            >>
            >> The other thing I'd recommend is stick that long list of fields in a
            >> list, and then do operations on that list:
            >>
            >> fields = ['delete_id', 'delete_date', 'delete_purchas etype',
            >> 'delete_price', 'delete_comment ']
            >>
            >> then to see if all those fields are empty:
            >>
            >> everything = ""
            >> for field in fields:
            >> everything += form.get(field, "")[/color]
            >
            >
            > Or everything = "".join(form.ge t(field, "") for field in fields)
            >
            > Somewhat labour-intensive. It appears from the OP's description that no
            > other entries can exist in the dictionary. If this is so, then:
            >
            > everything = "".join(form.va lues())
            >
            > but what the user sees on screen isn't necessarily what you get, so:
            >
            > everything = "".join(form.va lues()).strip()
            >[color=green]
            >> if everything == "":
            >> print "Absolutely nothing entered!"
            >>[/color][/color]

            Comment

            • John Machin

              #7
              Re: multiple parameters in if statement

              On 17/04/2006 5:13 AM, John Zenger top-posted:[color=blue]
              > Yup, join is better. The problem with using form.values() is that it
              > will break if the HTML changes and adds some sort of new field that this
              > function does not care about, or if an attacker introduces bogus fields
              > into his query.[/color]

              If one is worried about extra keys introduced by error or malice, then
              one should check for that FIRST, and take appropriate action. Code which
              is concerned with the values attached to the known/valid keys can then
              avoid complications caused by worrying about extra keys.
              [color=blue]
              >
              > John Machin wrote:[color=green]
              >> On 16/04/2006 1:43 PM, John Zenger wrote:
              >>[color=darkred]
              >>>
              >>> The other thing I'd recommend is stick that long list of fields in a
              >>> list, and then do operations on that list:
              >>>
              >>> fields = ['delete_id', 'delete_date', 'delete_purchas etype',
              >>> 'delete_price', 'delete_comment ']
              >>>
              >>> then to see if all those fields are empty:
              >>>
              >>> everything = ""
              >>> for field in fields:
              >>> everything += form.get(field, "")[/color]
              >>
              >>
              >> Or everything = "".join(form.ge t(field, "") for field in fields)
              >>
              >> Somewhat labour-intensive. It appears from the OP's description that
              >> no other entries can exist in the dictionary. If this is so, then:
              >>
              >> everything = "".join(form.va lues())
              >>
              >> but what the user sees on screen isn't necessarily what you get, so:
              >>
              >> everything = "".join(form.va lues()).strip()
              >>[color=darkred]
              >>> if everything == "":
              >>> print "Absolutely nothing entered!"
              >>>[/color][/color][/color]

              Comment

              Working...