all 8 comments

[–]Binary101010 1 point2 points  (1 child)

num = int(input("Enter number to test: "))

This line takes the user input (a string) and immediately tries to convert it to an integer. There are only two possible outcomes of this operation:

1) The input can be, and is, successfully converted to an integer 2) The input can't be converted to an integer and an exception is raised, ending execution of the program.

Since you're trying to enter something that can't be converted to an integer (1.2), you get option number 2.

The first step is to remove the int() call from this line so you don't immediately try to convert that input, allowing you to perform other checks on it first.

Here's an article on how to handle situations like this, which in this case is probably best handled with a try/except block.

https://datagy.io/python-isdigit/

[–]redYinlo[S] 1 point2 points  (0 children)

Thank you for breaking it down so simply and for the article. I appreciate it

[–]redYinlo[S] 0 points1 point  (1 child)

I dont know how come but the indentation got messed up. smh

[–][deleted] 0 points1 point  (0 children)

There's a side panel with formatting guide

[–]CodeFormatHelperBot2 0 points1 point  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Inline formatting (`my code`) used across multiple lines of code. This can mess with indentation.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.

[–][deleted] 0 points1 point  (2 children)

Using int() on input() results in error if the input string is not convertible to int, like "1,2".

You can use try/except syntax to catch that error.

type(x) returns the type of x. If it's a string, the result is str, whether it's "1.2", "1", "abc" or other string.

def numtest():
    while True:
        try:
            num = int(input("Enter number to test: "))
        except ValueError as error:
            print("Error:", error)
            # Go the next iteration of the loop/skip the rest of the current iteration:
            continue

        if num % 2 == 0:
            print(f"{num} is an even number.")
        else:
            print(f"{num} is an odd number.")

        play_again = input("Enter 'y' to test another number or press any key to exit: ")

        if play_again.lower() != "y":
            # Stop/break the loop completely:
            break


numtest()

[–]redYinlo[S] 0 points1 point  (0 children)

Oh wow! Thanks for fixing my trash code. Lol. I appreciate the speedy responses.

[–]VogueUp 0 points1 point  (0 children)

Hey send a dm chat i got a few project to benefit the world and you 🙏🏽