By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
 443,907 Members | 1,832 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

Multiple conditions in a single IF

 P: 16 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: Expand|Select|Wrap|Line Numbers 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: Expand|Select|Wrap|Line Numbers 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. Nov 16 '10 #1
Share this Question
4 Replies

 Expert Mod 2.5K+ P: 2,851 To determine if a variable is a multiple of 2 or 5, use the modulo operator. Expand|Select|Wrap|Line Numbers >>> m = 12 >>> m % 2   >>> 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: Expand|Select|Wrap|Line Numbers >>> 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: Expand|Select|Wrap|Line Numbers >>> m in [3,6,9,12,15] True >>>  Nov 16 '10 #2

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

 Expert 100+ P: 983 @Gonzalo Gonza - build composite conditions, something like this: Expand|Select|Wrap|Line Numbers 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. Nov 16 '10 #4

 Expert 100+ P: 624 Note that the variable "m" in not known to the function Expand|Select|Wrap|Line Numbers def asdf(n):     n=str(m) Also Expand|Select|Wrap|Line Numbers     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. Nov 17 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.