Finding Even Numbers In Python

和自甴很熟 提交于 2019-12-02 11:45:26

问题


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

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



回答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.

  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 i.e. 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.


来源:https://stackoverflow.com/questions/28390730/finding-even-numbers-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!