0

Question: Create an if-else conditional statement where a user inputs a number and outputs positive, negative, zero or string number.

num = input("Input: ")
if num > 0:
   print("Output: Positive")
elif num < 0:
    print("Output: Negative")
elif num == 0:
    print("Output: Zero")
else:
    print("Output: String Number")
Jimmy Hou
  • 1
  • 2
  • `input(...)` *always* returns a string, so you must try to cast it to an integer (using e.g. `try/except`). Afterwards, use `isinstance(...)`. With your snippet, you'll always get `Output: String Number`. – Jan May 24 '21 at 07:26

2 Answers2

1

Try using this:

num = int(input("Enter Number: "))

This will ensure that the number the user inputs is an int.

It'll raise an error if the number is a decimal or isn't a number at all.

You can use try and except to catch the error if the string is not a number.

potato
  • 79
  • 1
  • 11
  • Thanks, when I do the above the input returns an error when the input is a string. Is there a way to have both work and the "string number" input can be identified? – Jimmy Hou May 24 '21 at 07:35
  • I'm not sure I understand but you can use a try and except statement to check if the string is a number or just a normal string. https://www.w3schools.com/python/python_try_except.asp – potato May 24 '21 at 07:40
1

Use try except

try:
    num = int(input("input: "))

    if num > 0:
        print("Output: Positive")
    elif num < 0:
        print("Output: Negative")
    elif num == 0:
        print("Output: Zero")
except:
    print("Output: String Number")
Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25
  • Thank you for the reply, but is there a way to do this where the input can identify if the string is a string number or just a string? Because for the above code, any string I enter will output string number, but the question specifies only string numbers which are "12345" and "five" i think – Jimmy Hou May 24 '21 at 07:31
  • `input` will always return `string` type, no matter what you type in the input box. Whether you type `12345` or `five`, it will always return string type. In the above code, if the user input number then it will only execute `try` block otherwise it will only execute `except` block. Execute above code to check the difference – Prakash Dahal May 24 '21 at 07:41