0

I need to write a code that checks that the user input is a positive integer between 1 and 9. And if a string or negative integer is provided the program will display a message that reads "You have not entered a valid number - 0 has been stored instead." The code below does work. But if the user input is -5 the error message displays twice and I only need it to display once. I'm doing something wrong, but I don't know what.

try:
    x = input("Enter the first number:")
    x = int(x)
except:
    print("You have not entered a valid number - 0 has been stored instead")
    x = 0
if x < 1 or x > 9:
    print("You have not entered a valid number - 0 has been stored instead")
    x = 0
print(x)
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • Not reproductible, `Python 3.10.12`, latest `LinuxMint` – Gilles Quénot Aug 24 '23 at 22:37
  • I think you mean if x less than 0 ... – user19077881 Aug 24 '23 at 23:02
  • 1
    " I'm doing something wrong, but I don't know what." Think carefully about the logic, a step at a time. Suppose an exception is raised because the input is not valid. What will be the value of `x` after that point? Therefore, where the code says `if x < 1 or x > 9:`, what will happen? – Karl Knechtel Aug 24 '23 at 23:52
  • The value of x should be 0 if the input is not valid (i.e., it is a string or integer not between 1 and 9). – Tashi Higgins Aug 25 '23 at 04:08
  • @user19077881 - yep! if x less than 0 has resolved printing it twice. – Tashi Higgins Aug 25 '23 at 12:47
  • This isn't a direct answer to your question, but this syntax for checking that an integer is inside of a range should help you: [Determine whether integer is between two other integers](https://stackoverflow.com/questions/13628791/determine-whether-integer-is-between-two-other-integers) – Joe Sadoski Aug 25 '23 at 20:31

1 Answers1

0

The answer to your question is as follows:

try:
    x = input("Enter the first number:")
    x = int(x) 
    if 1<=x<=9: #this checks if the input is inbetween 1 and 9
        pass #here you can add an action that you want to happen when the if clause is true
    else:
        print("This number is out of the valid range (1,9). 0 has been stored instead")
        x=0
except ValueError:
        print("Error: You have not entered a valid value - 0 has been stored instead")
        x=0

print(x)