eskoka
eskoka

Reputation: 97

Restarting my program based on user input on Python?

I'm new to programming, fyi. I want my program to restart back to the top based on what the user inputs. It will proceed if the user inputs 2 names. If they input 1 name or more than 2 names, it should restart the program but I'm not sure of how to do this.

def main():
    print("Hello, please type a name.")
    first_name, last_name = str(input("")).split()
    while input != first_name + last_name:
        print("Please enter your first name and last name.")
main()

Upvotes: 0

Views: 384

Answers (2)

liminal_
liminal_

Reputation: 91

Use try/except

Well, your program didn't work for me to begin with, so to parse the first and last names simply, I suggest:

f, l = [str(x) for x in raw_input("enter first and last name: ").split()]

Also your while loop will just, like, break your life if you run it without good 'ol ctrl+c on hand. So, I suggest:

def main():
  print “type your first & last name”
  try:
    f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
    if f and l:
      return f + ‘ ‘+ l
  except:
    main()

The except: main() will re-run the program for you on error.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180421

You should use a while loop and check the length of the split before assigning:

def main():
    while True:
        inp = input("Please enter your first name and last name.")
        spl = inp.split()
        if len(spl) == 2: # if len is 2, we have two names
            first_name, last_name = spl 
            return first_name, last_name # return or  break and then do whatever with the first and last name

Upvotes: 1

Related Questions