Multiple conditions in a single IF

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Gonzalo Gonza
    New Member
    • Nov 2010
    • 16

    Multiple conditions in a single IF

    I want to know whether a number is a multiple of 2 and/or 5
    But Python doesn't let me put lots of things after the '=='

    Here's my code:
    Code:
    def asdf(n):
    	n=str(m)
    	if n==2:
    		a=True
    	elif n==5:
    		a=True
    	elif m[-1:]==2 or 4 or 6 or 8 or 0 or 5:
    		a=True
    I also tried:
    Code:
    elif m[-1:]==2, 4, 6, 8, 0, 5:
    But it doesn't make sense

    I wish you could help me
    Thank you

    PS: I know that the program don't make any sense but that's not the real purpose, it's just to simplify.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    To determine if a variable is a multiple of 2 or 5, use the modulo operator.
    Code:
    >>> m = 12
    >>> m % 2
    0
    >>> m % 5
    2
    >>> if not m % 2:
    ... 	print "m is a multiple of 2"
    ... 	
    m is a multiple of 2
    >>>
    To check multiple conditions in one statement:
    Code:
    >>> m = 15
    >>> if not m % 2 or not m % 5:
    ... 	print "m is a multiple of 2 or m is a multiple of 5"
    ... 	
    m is a multiple of 2 or m is a multiple of 5
    >>> not m % 2 or not m % 5
    True
    >>> not m % 2
    False
    >>> not m % 5
    True
    >>>
    A variable can also be checked for membership:
    Code:
    >>> m in [3,6,9,12,15]
    True
    >>>

    Comment

    • Gonzalo Gonza
      New Member
      • Nov 2010
      • 16

      #3
      Thank you, but I forgot to say that this funcion will recieve huge numbers, and the method with the module would be very inefficient.

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        @Gonzalo Gonza - build composite conditions, something like this:

        Code:
        def asdf(n):
          if (((n % 2) == 0) or ((n % 5) == 0)):
            result = True
          else:
            result = False
        
        def fdsa(n)
          result = (((n % 2) == 0) or ((n % 5) == 0))
        If I've a syntax error, please forgive me; I'm looking at python and trying to learn.

        Comment

        • dwblas
          Recognized Expert Contributor
          • May 2008
          • 626

          #5
          Note that the variable "m" in not known to the function
          Code:
          def asdf(n):
              n=str(m)
          Also
          Code:
              elif m[-1:]==2 or 4 or 6 or 8 or 0 or 5:
          #
          #   m would have to be a string or list to do a [-1], so compare 
          #   to strings  (compare to integers is m is a list of integers)
              elif m[-1] in ['2', '4', '6', '8', '0', '5']:
          [2, 4, 6, 8, 0, 5] should give you all numbers divisible by 2 or 5, I think.

          Comment

          Working...