Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading