Finding Even Numbers In Python

后端 未结 2 1765
暗喜
暗喜 2021-01-25 18:24

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

相关标签:
2条回答
  • 2021-01-25 18:39

    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")
    
    0 讨论(0)
  • 2021-01-25 19:02

    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.
    
    0 讨论(0)
提交回复
热议问题