User input range for num of rooms is [1-8]. Invalid input for this should display 'invalid input' and keep reprompt until receive valid input for executing the rest of the program. I've made it so invalid input for services returns and 'invalid service', the same should be done for input of num of rooms.
def main():
small = 60
medium = 120
large = 145
servOne = 40
servTwo = 80
numRooms = int(input("Number of rooms in the house?: "))
while True:
restart = int(input("Sorry Invalid number of rooms,try again? "))
if int(numRooms) < 1 or int(numRooms) > 8 in restart:
continue
(???)
servType = input("Type of cleaning service requested? (carpet cleaning or window cleaning): ")
if int(numRooms) <= 2:
print("Calculating fees for small house...")
if servType == "carpet cleaning":
print("Total cost of service:$",(small+servOne))
elif servType == "window cleaning":
print("Total cost of service:$",(small+servTwo))
else:
print("Sorry! Invalid service input")
if int(numRooms) >= 3 and int(numRooms) <= 5:
print("Calculating fees for medium house...")
if servType == "carpet cleaning":
print("Total cost of service:$",(medium+servOne))
elif servType == "window cleaning":
print("Total cost of service:$",(medium+servTwo))
else:
print("Sorry! Invalid service input")
if int(numRooms) >= 6:
print("Calculating fees for large house...")
if servType == "carpet cleaning":
print("Total cost of service:$",(large+servOne))
elif servType == "window cleaning":
print("Total cost of service:$",(large+servTwo))
else:
print("Sorry! Invalid service input")
main()
just wrap input in a while loop. if valid input is recieved, you end the loop
valid_input=False
while not valid_input:
i=input("Number of rooms in the house?:")
inp=int(i)
if inp in range(1,9): #(9 is not included)
valid_input=True
.
.
remaining code
.
.
another way to write above..easier to understand
while 1==1: # repeat loop(all statements below) forever
i=input("Number of rooms in the house?:")
inp=int(i)
if inp in range(1,9): #(9 is not included)
break # break out of the forever loop
#end of loop
One option (If I assume what you are trying to do) is to have a recursive function instead of a while loop, and call the function again on invalid input:
def Main():
validnums = [1,2,3]
i = Input("Please Enter input")
if int(i) not in validnums:
Main()
else:
##Do stuff
Main()
By having Main() call Main(), it functions identical to a while loop but you can restart it anytime. I hope this helps.
If you want to avoid recursion:
def Main():
validnums = [1,2,3]
While True:
i = input()
if int(i) not in validnums:
break
Main()
This uses a while loop and the function only calls itself when it needs to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.