简体   繁体   中英

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 are even. Otherwise the program outputs Not Both Even ."

I planned on using an if and else statement, but since I'm working with two numbers that have to be even instead of one, how would I do that?

Here is how I would do it if it was one number. Now how do I add the second_int that a user inputs???

if first_int % 2 == 0:
    print ("Both even")
else: print("Not Both Even")

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")

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.

  1. Use raw_input to get values from User.
  2. Use type casting to convert user enter value from string to integer .
  3. Use try excpet to handle valueError .
  4. Use % to get remainder by dividing 2
  5. Use if loop to check remainder is 0 ie number is even and use and operator to check remainder of tow numbers.

code:

while  1:
    try:
        no1 = int(raw_input("Enter first number:"))
        break
    except ValueError:
        print "Invalid input, enter only digit. try again"

while  1:
    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==0 and 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM