-2

I need to make small program that checks if number is divisible by two numbers at same time, if not it will not output anything.

Example 6 is true but 3 is false.

I tried this, but in sometimes it outputs even its not.

number = int(input("Give number: "))
if number % 2 and number % 3:
    print("True")
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    If you want to find out if the number is divisible by any two (distinct) numbers you will have to calculate its prime factors. You also aren't using the module operator correctly. – Jan Wilamowski Aug 16 '21 at 07:02
  • 1
    For what values does this give you an incorrect answer, and what answer do you expect? Are you looking for numbers that are divisible by any two numbers, or divisible by both 2 and 3? – JeffUK Aug 16 '21 at 07:07
  • 2
    Does this answer your question? [How do you check whether a number is divisible by another number (Python)?](https://stackoverflow.com/questions/8002217/how-do-you-check-whether-a-number-is-divisible-by-another-number-python) – mkrieger1 Aug 16 '21 at 07:11

3 Answers3

1

To determine if a number is evenly divisible by x, you should check if number % x == 0, and you are effectively doing the exact opposite of that.

When writing expressions with multiple operators in them like the previous or in even more complicated cases like this

number % 2 == 0 and number % 3 == 0

To get things right you need to take into consideration the default operator precedence, which is order they will be performed in if no parentheses are present to override it. This means that without them, the expression will evaluated in this order:

((number % 2 == 0)) and ((number % 3 == 0))

which happens to be exactly what is needed in this case, so their use is not required. Folks sometimes put some of them in anyhow, just to make what's going on clearer. E.G.:

(number % 2 == 0) and (number % 3 == 0)
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Below update in code will definitely solve your problem.

number = int(input("Give number: "))
if (number % 2)==0 and (number % 3)==0:
    print("True")
  • 1
    See [What comment should I add to code-only answers?](https://meta.stackoverflow.com/questions/300837/what-comment-should-i-add-to-code-only-answers) – martineau Aug 16 '21 at 07:53
0

Your code is almost correct, but you miss the equal "==" sign in your condition. Try this:

number = int(input("Give number: "))
if number % 2 == 0 and number % 3 == 0:
    print("True")