-4

I have this code:

applesToday = input('Hope you\'re having a nice day! How many apples have you\'ve eaten?')
if applesToday >= str(1) and applesToday< str(2):
    print('You\'ve had 1 apple')
elif applesToday < str(1) and applesToday >= str(0):
    print('You\'ve had 0 apples')
else:
    print('You\'ve had {0} apples,'.format(applesToday))

The problem is that the code accepts non-integer inputs, and successfully compares them.

How can I make it so that the code only takes an integer, and does proper numeric comparisons?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Soto
  • 1
  • 1
  • Format the code correctly (button `{}` in the editor helps). – Michael Butscher May 20 '23 at 10:10
  • Welcome to Stack Overflow. Please read [ask] and note well that this is **not a discussion forum**. We do not want questions here to talk about you or your experience as a programmer - they should be **questions only**, about **the code**. I tried to fix the question in order to show the code, ask about the apparent problem directly, and use a title that explains the problem (don't use this to plead for help). – Karl Knechtel May 20 '23 at 10:14
  • Please also read the [formatting help](https://stackoverflow.com/help/formatting) in order to understand how to format code properly. I attempted to fix this for you; since you did not complain about any syntax error, I assumed that you had working (properly indented) code. Since indentation is important in Python, it is important to make sure that the code appears in your post exactly as you actually have it. Please **check the post preview** before posting questions. – Karl Knechtel May 20 '23 at 10:16
  • More importantly, though: [please try](https://meta.stackoverflow.com/questions/261592) to look for existing Q&A before posting - this starts with coming up with a clear description of the problem (not just talking through it in a forum post, since again this is **not a discussion forum**) and then using the site search or an external search engine. We get the general form of this question **constantly**. – Karl Knechtel May 20 '23 at 10:17
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – rene May 20 '23 at 10:28

1 Answers1

-1

Almost there use code below:

try :
    applesToday = int(input("Hope you're having a nice day! How many apples have you've eaten?")) 
    if applesToday < 0:
        print('Negative apples is not possible')
    elif applesToday >= 1 and applesToday< 2: 
        print('You\'ve had 1 apple') 
    elif applesToday < 1 and applesToday >= 0: 
        print('You\'ve had 0 apples') 
    else: 
        print("You've had {0} apples,".format(applesToday))
except ValueError:
    print("Invalid input. Please enter a positive number.")

Happy learning.

Suchandra T
  • 569
  • 4
  • 8