Jackson Tai
Jackson Tai

Reputation: 493

How to avoid using to much if else?

This is the concept of what I'm trying to acheive with the code. I want the user to be able to leave the login section whenever they press '0', the codes below works, but is there anyway that I can shorten these codes, cause I felt like there's too much if else being use.

def signup():
     print("Press '0' to return mainpage")
     firstname = input("Please enter your first name : ")
     if firstname == "0":
          print("Mainpage returned")
          mainpage()
     else:
          lastname  = input("Please enter your last name  : ")
          if lastname == "0":
               print("Mainpage returned")
               mainpage()
          else:
               username = firstname+lastname
               print("Welcome", username)

def mainpage():
     option = input("Press '1' to signup: ")
     if option == '1':
          print("Sign up page accessed")
          signup()
mainpage()

Upvotes: 2

Views: 509

Answers (2)

Prune
Prune

Reputation: 77827

First of all, write code that matches your true logic. This potentially infinite recursion is inappropriate. This is a nested process, not something innately recursive.

You say that you want to leave the signup area when the user inputs 0. If so, then leave -- don't go down yet another "rabbit hole": delete those calls to mainpage and return normally. After all, mainpage is where you came from.

As for using fewer if statements, you can't reduce this much without very much generalizing the interactions in your program. You want to check for 0 in two places and for 1 in another. This requires either 3 if checks or a process general enough to make all of the transitions given a list of legal "moves". If you want that, please look up how to implement a finites state machine.

However, there is one straightforward economy: your user interface is unduly wordy. Just ask for the entire name at once:

def signup():
     print("Press '0' to return mainpage")
     username = input("Please enter your name : ")
     if name == "0":
         print("Mainpage returned")
     else:
         username.replace(' ', '')    # remove space(s)
         print("Welcome", username)

Either way, this routine naturally returns to mainpage.

Upvotes: 1

Stephen Jennings
Stephen Jennings

Reputation: 13234

You could use early returns to remove some of the nesting.

def signup():
     print("Press '0' to return mainpage")
     firstname = input("Please enter your first name : ")
     if firstname == "0":
          print("Mainpage returned")
          mainpage()
          return
 
     lastname  = input("Please enter your last name  : ")
     if lastname == "0":
         print("Mainpage returned")
         mainpage()
         return

     username = firstname+lastname
     print("Welcome", username)

Upvotes: 4

Related Questions