Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Shortening Code

I'm quite new to programming in Python. I have always written my int inputs like the following example to ensure a user inputs an int. This is a specific example I have in my code that I'm sure I can shorten and thus learn for future projects.

This ensures a three digit number is input by creating a loop that breaks when a three digit number is entered.

while 1 == 1:
  print("Input a 3 digit number")
    #The try statement ensures an INTEGER is entered by the user
    try:
      x = int(input())
      if 100 <= x < 1000:
        break
      else:
        print()
    except ValueError:
      print()
like image 708
Webber Avatar asked Feb 24 '26 02:02

Webber


1 Answers

You can do something like this:

while True:
    x = input("Input a 3 digit number: ")
    if x.isdigit() and 100 <= int(x) <= 999:
        break

isdigit() checks whether the string consists of digits only (won't work for floats). Since Python uses short-circuiting to evaluate boolean expressions using the operator and, the second expression 100 <= int(x) <= 999 will not be evaluated unless the first (x.isdigit()) is true, so this will not throw an error when a string is provided. If isdigit() evaluates to False, the second expression won't be evaluated anyway.

Another option is the following:

condition = True
while condition:
    x = input("Input a 3 digit number: ")
    condition = not (x.isdigit() and 100 <= int(x) <= 999)
like image 61
Rafael Avatar answered Feb 25 '26 16:02

Rafael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!