Home > database >  Am I using boolean operations correctly?
Am I using boolean operations correctly?

Time:10-08

For an assignment for class, I am needing to create a program that returns if a number is even or odd, while having the main function get user input and displays the output, while another function checks whether the number is even or odd. My python knowledge so far is very basic. Here is what I've got so far.

def check(number):
    if (number % 2) == 0:
        return True
    else:
        return False

def main():
    number = int(input("Enter an integer: "))
    if check is True:
        print("This is an even number.")
    elif check is False:
        print("This is an odd number.")


__name__ == "__main__"
main()

When I run the code, I get the input prompt, but nothing in return after.

CodePudding user response:

check is a function, so it should be like

if check(number):
    print("This is an even number.")
else:
    print("This is an odd number.")

CodePudding user response:

Python is very flexible, you don't even need a function.

I would take advantage of f-strings and a ternary:

number = int(input("Enter an integer: "))
print(f'This is an {"odd" if (number % 2) else "even"} number')

Example:

Enter an integer: 2
This is an even number

Enter an integer: 3
This is an odd number

CodePudding user response:

  • As you are basic this is not the best function for check using bool.
   def check(num):
       return num % 2 == 0 # return True if even otherwise odd
  • This code is simple and easily to read rapidly.
  • Related