-1

I am fairly new to Python and I'm trying to create a simple program to calculate, then print, how much a vacation rental is based on the number of weeks a user has inputted (so long as the number of weeks is greater than 4, but less than 16). I have that part of the code down just fine, but what I am having trouble with is getting the program to repeat the question if a user does enter a number that is not in range. Any help would be greatly appreciated. Here is my code:

weeks = 0
total = 0

while True:
    try:
        weeks = int(input("How many weeks do you plan on vacationing? "))
        break
    except ValueError:
        print("Please enter a number.")

if weeks < 4:
    print("Not in range.")
elif weeks <= 6:
    total = weeks*3080
    print("Rental cost: $",total)
elif weeks <= 10:
    total = weeks*2650
    print("Rental cost: $", total)
elif weeks <=16:
    total = weeks*2090
    print("Rental cost: $", total)
else:
    print("Not in range.")

Update:


weeks = 0
total = 0

while True:

    try:
        weeks = int(input("How many weeks do you plan on vacationing? "))

        if weeks < 4:
            print("Not in range.")
            continue
        elif weeks <= 6:
            total = weeks*3080
            print("Rental cost: $",total)
            break
        elif weeks <= 10:
            total = weeks*2650
            print("Rental cost: $", total)
            break
        elif weeks <=16:
            total = weeks*2090
            print("Rental cost: $", total)
            break
        else:
            print("Not in range.")

    except ValueError:
        print("Please enter a number.")
Andy K
  • 4,944
  • 10
  • 53
  • 82
Jordan Jackson
  • 9
  • 1
  • 2
  • 5
  • If it helps, I just ran this and it worked perfectly for me. What is the actual error / bug you're getting? – Jordan Nov 22 '17 at 20:19
  • `while True: weeks = input("How many weeks do you plan on vacationing? ") if weeks.isdigit()==False: print("Please enter a number.") else: weeks=int(weeks) break ` – whackamadoodle3000 Nov 22 '17 at 20:22
  • I don't think this question is a duplicate - but maybe if you re-post again but focus on the bug you're getting. – Jordan Nov 22 '17 at 20:22
  • I wasn't getting a bug or error per se, but when the user inputted a number that was less than 4 or more than 16, the program stopped instead of repeatedly asking for a number until it received one in range. However, I was able to remedy this by checking out the question user1767754 posted as a duplicate. Thanks for the interest in helping though, I do appreciate it! – Jordan Jackson Nov 22 '17 at 20:22
  • You can also try to indent my code in the comment – whackamadoodle3000 Nov 22 '17 at 20:23

1 Answers1

0

Validate weeks in the try block and raise ValueError before the break if out of range.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251