How to return to previous part of the program (Python)
I'm novice in python and got a problem in which I would appreciate some help. The problem in short:
- ask for a string
- check if all letter in a predefined list
- if any letter is not in the list then ask for a new string, otherwise go to next step
- ask for a second string
- check again whether the second string's letters in the list
- if any letter is not in the list then start over with asking for a new FIRST string
basicly my main question is how to go back to a previous part of my program, and it would also help if someone would write me the base of this co开发者_Go百科de. It start like this:
list1=[a,b,c,d]
string1=raw_input("first:")
for i in string1:
if i not in list1:
Thanks
I suggest you start here: http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming
And continue to next chapter: http://docs.python.org/tutorial/controlflow.html
You have a couple of options, you could use iteration, or recursion. For this kind of problem I would go with iteration. If you don't know what iteration and recursion are, and how they work in Python then you should use the links Kugel suggested.
This sounds like a job for a while loop http://www.tutorialspoint.com/python/python_while_loop.htm
pseudo code is
list=[a,b,c,d]
declare boolean passes = false
while (!passes)
passes = true
String1 = raw_input("first:")
foreach char in string1
if !list.contains(char)
passes = false
break
if passes
String2 = raw_input("second:")
foreach char in string2
if !list.contains(char)
passes = false
break
Another good place to start is by looking for common sequences of action and putting them in a separate subroutine.
# ignore this bit - it's here for compatibility
try:
inp = raw_input # Python 2.x
except NameError:
inp = input # Python 3.x
# this wraps the 'ask for a string, check if all characters are valid' bit in a single call
def GetValidString(msg, validChars):
i = inp(msg)
if all(ch in validChars for ch in i):
return i
else:
return None
def main():
while True:
str1 = GetValidInput('first: ', 'aeiou'):
if str1:
str2 = GetValidInput('second: ', 'rstvy'):
if str2:
break # good! we can leave the loop now
# got valid values for str1 and str2
the logic looks like 'loop until you get string1 and it is good and you get string2 and it is also good'.
Hope that helps.
精彩评论