Q. Write equivalent code for code given below using if-else and if elif-else statements.

dividend_str = input ("Enter an integer to divide: ")
divisor_str = input ("Enter an integer to divide it by: ")
dividend_int = int(dividend_str)
divisor_int = int(divisor_str)
if divisor_int == 0:
    print ("Divisor is:", divisor_int)
    print ("Can't divide by 0")
    print ("Run the program again and enter a non-zero divisor")
if divisor_int != 0:
    print ("The result of", dividend_str, "/", \
           divisor_str, "is:", dividend_int/divisor_int)
print ("Thank You")

(For if-elif-else create a test case when divisor is 1; displaying that dividing by 1 gives the same number.)

if-else :-

if-elif-else :-


Answer :-

Using if-else :-

dividend_str = input ("Enter an integer to divide: ")
divisor_str = input ("Enter an integer to divide it by: ")
dividend_int = int(dividend_str)
divisor_int = int(divisor_str)
if divisor_int == 0:
    print ("Divisor is:", divisor_int)
    print ("Can't divide by 0")
    print ("Run the program again and enter a non-zero divisor")
else:
    print ("The result of", dividend_str, "/", \
           divisor_str, "is:", dividend_int/divisor_int)
print ("Thank You")

Output :-

Enter an integer to divide: 45
Enter an integer to divide it by: 0
Divisor is: 0
Can't divide by 0
Run the program again and enter a non-zero divisor
Thank You

>>>
Enter an integer to divide: 25
Enter an integer to divide it by: 5
The result of 25 / 5 is: 5.0
Thank You

>>>

Using if-elif-else :-
dividend_str = input ("Enter an integer to divide: ")
divisor_str = input ("Enter an integer to divide it by: ")
dividend_int = int(dividend_str)
divisor_int = int(divisor_str)
if divisor_int == 0:
    print ("Divisor is:", divisor_int)
    print ("Can't divide by 0")
    print ("Run the program again and enter a non-zero divisor")
elif divisor_int == 1:
    print ("Divisor is:", divisor_int)
    print ("dividing by 1 gives the same number")
else:
    print ("The result of", dividend_str, "/", \
           divisor_str, "is:", dividend_int/divisor_int)
print ("Thank You")

Output :-

Enter an integer to divide: 45
Enter an integer to divide it by: 5
The result of 45 / 5 is: 9.0
Thank You

>>> 
Enter an integer to divide: 63
Enter an integer to divide it by: 1
Divisor is: 1
dividing by 1 gives the same number
Thank You

>>> 
Enter an integer to divide: 89
Enter an integer to divide it by: 9
The result of 89 / 9 is: 9.88888888888889
Thank You

>>> 

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post