This is my code for my attempt to validate 4 input codes
while True:
try:
customer_name = input("Enter updated customer name: ")
if not customer_name.isalpha():
print("Customer names should not contain numbers!")
continue
package_name = str(input("Enter updated package name: "))
if not package_name.isalpha():
print("Package names should not contain numbers!")
continue
number_pax = int(input("Enter updated pax: "))
pax_cost = int(input("Enter updated cost per pax: $"))
except ValueError:
print("Invalid input, only numbers allowed!")
continue
What I would like to do is for example, when a user enters a str for number_pax
it will show an error message but lets users to try again for that specific input. However, my codes brings the user back to the first input code which is customer_name
How may I do so to let the user continue from the input code they were at and not start from the first one(customer_name) again.
I hope I have worded it properly enough, all help is greatly appreciated!
CodePudding user response:
You should put each validation inside it's own while
loop. Since this would require you to write the same code multiple times, it's a candidate for using functions:
def get_input_number(question: str) -> int:
result = input(question)
while not result.isnumeric():
print("Only numeric input is allowed")
result = input(question)
return int(result)
def get_input_alpha(question: str) -> str:
result = input(question)
while not result.isalpha():
print("Only alpha input is allowed")
result = input(question)
return result
customer_name = get_input_alpha("Enter updated customer name:\n")
package_name = get_input_alpha("Enter updated package name:\n")
number_pax = get_input_number("Enter updated pax:\n")
pax_cost = get_input_number("Enter updated cost per pax: $\n")
CodePudding user response:
In this case, we can work with each input as a function
customer_name = ""
package_name = ""
number_pax = 0
pax_cost = 0
def customerName():
customer_name = input('Enter Updated Customer Name: ')
if customer_name.isalpha() == False :
print("Customer Name Contains Only Letters")
customerName()
def packageName():
package_name = input('Enter Package Name: ')
if package_name.isalpha() == False:
print("Package Name Contains Only Letters" )
packageName()
def numberPax():
try:
number_pax = int(input('Enter Number Pax: '))
except ValueError as err:
print('Only Numbers Allowed')
numberPax()
def paxCost() :
try:
pax_cost = int(input('Enter Pax Cost: '))
except ValueError as err:
print('Only Numbers Allowed, Try Again')
paxCost()
while True:
customerName()
packageName()
numberPax()
paxCost()