Home > front end >  how do i get it to ask again if year level put in is out of max and min
how do i get it to ask again if year level put in is out of max and min

Time:07-14

year = int(input("what year are you in?"))     

while (year) <MIN_YEAR or (year) > MAX_YEAR or not year.isalpha():
    print("Thats not within Carmels Year levels please try again


    year = int(input("what year are you     in?"))

CodePudding user response:

year = input("what year are you in?")
min_year, max_year = 2009, 2020
while not (year.isdigit() and min_year < int(year) < max_year):
    year = input("That's not within Carmels Year levels please try again:")
else:
    year = int(year)

print(year)

CodePudding user response:

What you have is mostly correct: you just have an extraneous and erroneous attempt to call year.isalpha (year is already an int at this point, not a str):

year = int(input("what year are you in?"))     

while (year) <MIN_YEAR or (year) > MAX_YEAR:
    print("Thats not within Carmels Year levels please try again")
    year = int(input("what year are you     in?"))

Switch to an infinite loop with a break statement to avoid duplicating the call to input.

while True:
    year = int(input("What year are you in?"))
    if MIN_YEAR <= year <= MAX_YEAR:
        break
    print("Thats not within Carmels Year levels please try again")

Now that we only have one call to input and int, we can add some additional error checking more easily. If you are going to call int anyway, let it check if the input is numeric as part of its normal functioning.

while True:
    year = input("What year are you in?")
    try:
        year = int(year)
    except ValueError:
        print("Not a valid year")
        continue

    if MIN_YEAR <= year <= MAX_YEAR:
        break
    print("Thats not within Carmels Year levels please try again")

CodePudding user response:

You might do something similar to the following code snippet.

MIN_YEAR = 1900
MAX_YEAR = 2525

def get_year():
    year = 1900
    
    while True:
        yr = input('What year are you in: ')
    
        if not yr.isnumeric():
            print('Please only enter numbers')
            continue
            
        if int(yr) < MIN_YEAR or int(yr) > MAX_YEAR:
            print('Entry must be in the range of ', MIN_YEAR, ' to ', MAX_YEAR)
            continue
            
        break
        
    return yr
    
year = get_year()

print('Entered year is :', year)

CodePudding user response:

Use a while True loop instead, and use the break keyword to exit the loop

while True:
    year = int(input("what year are you in?"))
    min = 2000
    max = 2010
    while not (min < year < max_year):
        print("That's not within Carmels Year levels please try again:")
    else:
       break
  • Related