Finding Even Numbers In Python
I have a Python assignment that is as following: 'Write a complete python program that asks a user to input two integers. The program then outputs Both Even if both of the integers
Solution 1:
You can still use an if else and check for multiple conditions with the if block
if first_int % 2 == 0 and second_int % 2 == 0:
print ("Both even")
else:
print("Not Both Even")
Solution 2:
An even number is an integer which is "evenly divisible" by two. This means that if the integer is divided by 2, it yields no remainder. Zero is an even number because zero divided by two equals zero. Even numbers can be either positive or negative.
- Use
raw_input
to get values from User. - Use
type casting
to convert user enter value fromstring
tointeger
. - Use
try excpet
to handlevalueError
. - Use
%
to getremainder
by dividing2
- Use if loop to check
remainder
is0
i.e. number iseven
and useand
operator to checkremainder
of tow numbers.
code:
while1:
try:
no1 = int(raw_input("Enter first number:"))
break
except ValueError:
print"Invalid input, enter only digit. try again"while1:
try:
no2 = int(raw_input("Enter second number:"))
break
except ValueError:
print"Invalid input, enter only digit. try again"print"Firts number is:", no1
print"Second number is:", no2
tmp1 = no1%2
tmp2 = no2%2
if tmp1==0and tmp2==0:
print"Both number %d, %d are even."%(no1, no2)
elif tmp1==0:
print"Number %d is even."%(no1)
elif tmp2==0:
print"Number %d is even."%(no2)
else:
print"Both number %d, %d are NOT even."%(no1, no2)
Output:
vivek@vivek:~/Desktop/stackoverflow$ python 7.py
Enter first number:w
Invalid input, enter only digit. try again
Enter first number:4
Enter second number:9
Firts number is:4
Second number is:9
Number 4 is even.
Post a Comment for "Finding Even Numbers In Python"