Computer Science, asked by anindyaadhikari13, 2 months ago

Correct the logical error in the given Python códe and also explain your answer.

n=int(input("Enter a number - "))
if n%5:
print("Number is divisible by 5.")
else:
print("Number is not divisible by 5.")​

Answers

Answered by atrs7391
6

Given Program:

n=int(input("Enter a number - "))

if n%5:

print("Number is divisible by 5.")

else:

print("Number is not divisible by 5.")​

Rectified Program:

n = int(input("Enter a number - "))

if n % 5 == 0:

   print("Number is divisible by 5.")

else:

   print("Number is not divisible by 5.")

Explanation:

On line 2, the condition for the if statement was not right, i.e. the if statement requires a Boolean value but the value was not a Boolean one.

On Line 3 and Line 5, there was a syntax error i.e. the indentations were not  given correctly.

Answered by BrainlyProgrammer
3

Given snippet:-

n=int(input("Enter a number - "))

if n%5:

‎ ‎ ‎ ‎print("Number is divisible by 5.")

else:

‎ ‎ ‎ ‎print("Number is not divisible by 5.")

___

What is an error in this snippet?

  • There is a logical error in this snippet where you actually want to check if the number is divisible by 5 or not.
  • But, the program returns not divisible though it is divisible by 5

_____

Why this error?

In Line no. 2, if n%5:

Now suppose if n=5 then 5%5=0.

Since there is no relational operators (like ==,<=,>=,etc) then this n%5 will return Boolean value that is True/False.

____

Note:-

  • In python, 0 means False and any non-zero number means True

Explaination of the error...

>>As I had already assumed n=5 let's solve with this..

5%5=0 which will be false as it is zero

Hence, it executes else part.

So your output will be:

Number is not divisible by 5.

>>Similarly if we we assume n= number not divisible by 5 (say,12), then 12%5=2

Now 2 is non-zero, therefore it will return True and executes the first statement.

So the output will be:

Number is divisible by 5.

How to remove this error?

>>There are two ways to get the desired output:-

Method 1:

n=int(input("Enter a number - "))

if n%5:

‎ ‎ ‎ ‎print("Number is not divisible by 5.")

else:

‎ ‎ ‎ ‎print("Number is divisible by 5.")

Method 2: Using "==" Operator

n=int(input("Enter a number - "))

if n%5==0:

‎ ‎ ‎ ‎print("Number is divisible by 5.")

else:

‎ ‎ ‎ ‎print("Number is not divisible by 5.")

♬••••♪

Similar questions