In this tutorial, you will create a Python program to find if a number is divisible by another number or not.
If you are new to Python, to understand this code, you should first check:
- How to get basic input and output in Python
- If and else conditional statements in Python
- While loop in python
Simple Code
num = int(input('Enter the number whose divisibility needs to be checked: '))
div = int(input('Enter the number with which divisibility needs to be checked: '))
if num % div == 0:
print('The two numbers are completely divisble by eachother.')
else:
print('The two numbers are not completely divisble by eachother.')
Enter the number whose divisibility needs to be checked: 30
Enter the number with which divisibility needs to be checked: 6
The two numbers are completely divisble by eachother.
Code with handling the wrong inputs such as alphabet and characters
while True:
try:
num = int(input('Enter the number whose divisibility needs to be checked: '))
div = int(input('Enter the number with which divisibility needs to be checked: '))
if num % div == 0:
print('The two numbers are completely divisble by eachother.')
else:
print('The two numbers are not completely divisble by eachother.')
break
except:
print('Invalid entry. Enter integer values.')
Output
Enter the number whose divisibility needs to be checked: lksdjf
Invalid entry. Enter integer values.
Enter the number whose divisibility needs to be checked: 30
Enter the number with which divisibility needs to be checked: 5
The two numbers are completely divisble by eachother.
Code with explanation (Exception handling)
#program will run until it is executed successfully!
while True:
#This try block will be executed first and if the user enter an interger, the result will be printed and program will end successfully
#But if the user enter wrong input such as an alphabet, program will throw an error and will run again
try:
#take input from the user
num = int(input('Enter the number whose divisibility needs to be checked: '))
div = int(input('Enter the number with which divisibility needs to be checked: '))
#check if the number is divisible by diviser
if num % div == 0:
print('The two numbers are completely divisble by eachother.')
else:
print('The two numbers are not completely divisble by eachother.')
#this break command will end the program if it is executed successfully.
break
#But in some cases, the user may enter some alphabet or any other character. Then this error will be displayed and loop will run the program again
except:
print('Invalid entry. Enter integer values.')
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.