MotorCity
MotorCity

Reputation: 11

Trying to create code that both verifies that a variable is numbers and has 4 or 5 characters long

I am trying to create code that takes a ZIP code and verifies that the input is numeric and that it's between 4 to 5 characters in length. This is the code I am trying to use. But if I put in letters, it doesn't print "Invalid Area Code", it just errors out.

zip_code = int(input("Please enter your area code: "))
if len(zip_code) == 4 or len(area_code) == 5 and zip_code.isnumeric(): 
    print (zip_code)
else:
     print("Invalid zip Code")

Upvotes: 0

Views: 48

Answers (2)

BrokenBenchmark
BrokenBenchmark

Reputation: 19252

There are two issues with your code:

  1. You're converting the input to an integer, then calling len() on it. You can call len() on strings, but not integers, so don't transform the input to an integer.
  2. area_code isn't defined. You're probably looking to use zip_code instead.

Here is a code snippet that resolves both of these issues:

zip_code = input("Please enter your area code: ")
if len(zip_code) == 4 or len(zip_code) == 5 and zip_code.isnumeric(): 
    print(zip_code)
else:
    print("Invalid ZIP code")

Upvotes: 1

TheFaultInOurStars
TheFaultInOurStars

Reputation: 3608

If a string is parsable to be an integer, meaning that it is actually a number, your code will work fine. But most of the time, user inputs can not be predicted. if you just use isnumeric or isdigit in your code, you won't have any problem.

Personally speaking, I use regex to validate user input in most of the cases. In your case, I came up with code below:

import re
string = input("Please enter your area code: ")
pattern = "^\d{4,5}$"
if re.search(pattern, string):
  print("Valid " + string)
else:
  print("Invalid zip Code")

Example of correct input:

1234

Output

Valid 1234

Example of incorrect input:

123415

Output:

Invalid zip Code

Explanation

re.search function takes two arguments. The first argument is a pattern which will check if the second argument, which is a string, follows the pattern or not. ^\d{4,5}$ checks if the user input is a number that has 4 or 5 digits.

Upvotes: 0

Related Questions