0

Why doesn't my Python code show the "thank you" message when the user types a positive number?

Code

x = int(input("give me a positif number"))
while x < 0:
    try:
        print ("it is not a positif number")
        x = int(input("give me a positif number"))
        break
    except ValueError:
        print("thank you")
        break
Community
  • 1
  • 1
Maher
  • 11
  • 1
  • 5
  • What exactly are you trying to do? The while loop will only execute if you type a negative number. – Jéssica Carneiro Feb 28 '20 at 17:32
  • you have complicated the code using both `while` loop and `try ` and `except`, code under `except` will only be executed if there is a value error,do you think postive no is a Value Error – Shubham Shaswat Feb 28 '20 at 17:35
  • @ShubhamShaswat seems a perfectly valid approach to me... just not done quite correctly. – Jon Clements Feb 28 '20 at 17:38
  • Maher - look at the accepted answer on the linked dupe under "Combining Exception Handling and Custom Validation" - you can pretty much use that code exactly but in the `else` put your "Thank you" – Jon Clements Feb 28 '20 at 17:40
  • @JonClements yes,the code will do work if written correctly but why not just use while loop like this, `while x < 0: x=int(input()) ` and then outside the loop `print(thank you)` – Shubham Shaswat Feb 28 '20 at 17:49
  • @ShubhamShaswat that doesn't cater for if any of the `x = int(input())`'s thrown an exception because it's not convertible to an int... it also means you then have the same repeated code of `x=int(input())` both outside the loop and inside... and that can lead to typos or forgetting to either put it inside the loop or outside leading to other pesky errors - the `x = int(input())` only needs to be done once and you can do that inside the while – Jon Clements Feb 28 '20 at 17:53
  • @ShubhamShaswat something like https://gist.github.com/ninjapuppydev/6accbbc0c96b99bf073d6eedc0dda3ee is a perfectly Pythonic way of covering exceptions, repeating the requests if needful and not having the input request both outside and inside a loop... – Jon Clements Feb 28 '20 at 18:02
  • @JonClements thanks for the code,now I actually understood what you were talking about. – Shubham Shaswat Feb 29 '20 at 10:03

0 Answers0