Reputation: 11
As a beginner, I want to make continue function in Python to go back to a specific line inside the loop not to start over without making double while loops, I will explain more by code.
The following program aims to take a name (letters only) and age (numbers only) from the user until valid inputs are given:
while True :
name=input ('please enter your first name with no numbers ')
if not name.isalpa():
print('incorrect input, please enter another input')
continue
age = input ('''please enter your age 'numbers only' ''')
if not age.isdecimal():
# I want to use continue heer to jump back to the
# age input line again not to the start of the loop
Upvotes: 0
Views: 594
Reputation: 308
Try this approach:
while True :
name=input ('please enter your first name with no numbers ')
while(!name.isalpa()):
print('incorrect input, please enter another input')
name=input ('please enter your first name with no numbers ')
age = input ('''please enter your age 'numbers only' ''')
while(!age.isdecimal()):
print('incorrect input, please enter another input')
age=input ('''please enter your age 'numbers only' ''')
Upvotes: 1
Reputation: 2522
That's for sure a bad design. You should validate one input and then ask for another. But you can accomplish what you are asking for with an additional boolean variable:
isNameOk = False
while True :
if not isNameOk:
name=input ('please enter your first name with no numbers ')
if not name.isalpa():
print('incorrect input, please enter another input')
continue
isNameOk = True
age = input ('''please enter your age 'numbers only' ''')
if not age.isdecimal():
print('incorrect input, please enter another input')
continue
But I would strongly suggest something like this with two while
s:
name = input ('please enter your first name with no numbers ')
while not name.isalpha():
name = input('please enter your first name with no numbers ')
age = input('please enter your age numbers only')
while not age.isdecimal():
age = input('please enter your age numbers only')
Upvotes: 0