Home > Net >  Is there anyway to make this python code better and more efficient?
Is there anyway to make this python code better and more efficient?

Time:07-09

I made a small python program to measure length of Username entered. If the length of Username is more than 6 characters, it prints "Username is valid", if length is less than 6 characters, it prints "Username must contain at least 6 characters" and if length is 0 (running the program without typing any characters), it prints "Username is required". Here is the code:

Name = input("Enter Your Name: ")

if(len(Name)>=6):
   print("Username is valid")
elif(len(Name)<6 and len(Name)>=1):
   print("Username should contain atleast 6 Characters")
else:
   print("Username is required")

I just want to know if I could do it better. Just a quick suggestion would do. Also, this is my first time posting a question, so any suggestions to improve my question asking format would also be appreciated.

CodePudding user response:

In this case, len(Name) is evaluated three times.

You can store the result in a variable, so that len(Name) is evaluated only once, and in the second and third occurrences you use that variable.

The performance difference is very negligible btw because it's a very small scale.

Another thing is variable names. In Python, we use snake_case to name variables by default for variables and UPPERCASED_TEXT for constants.

CodePudding user response:

I don't see anything "bad" about this simple program although I'd try to make it even more explicit and easier to read and understand. Something like this...

name = input("Enter your name: ")

if name != '':
    if len(name) < 6:
        print("username is not valid") 
    else:
        print(f"{name} is valid!")
else:
    print("username is required")

  • Related