Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Strong Password Suggester Program
Next article icon

Python program to check the validity of a Password

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this program, we will be taking a password as a combination of alphanumeric characters along with special characters, and checking whether the password is valid or not with the help of a few conditions.

Primary conditions for password validation:

  1. Minimum 8 characters.
  2. The alphabet must be between [a-z]
  3. At least one alphabet should be of Upper Case [A-Z]
  4. At least 1 number or digit between [0-9].
  5. At least 1 character from [ _ or @ or $ ].

Examples:

Input : R@m@_f0rtu9e$
Output : Valid Password

Input : Rama_fortune$
Output : Invalid Password
Explanation: Number is missing

Input : Rama#fortu9e
Output : Invalid Password
Explanation: Must consist from _ or @ or $

Way 1: 

Here we have used the re module that provides support for regular expressions in Python. Along with this the re.search() method returns False (if the first parameter is not found in the second parameter) This method is best suited for testing a regular expression more than extracting data. We have used the re.search() to check the validation of alphabets, digits, or special characters. To check for white spaces we use the “\s” which comes in the module of the regular expression. 

Python
# Python program to check validation of password # Module of regular expression is used with search() import re password = "R@m@_f0rtu9e$" flag = 0 while True:     if (len(password)<=8):         flag = -1         break     elif not re.search("[a-z]", password):         flag = -1         break     elif not re.search("[A-Z]", password):         flag = -1         break     elif not re.search("[0-9]", password):         flag = -1         break     elif not re.search("[_@$]" , password):         flag = -1         break     elif re.search("\s" , password):         flag = -1         break     else:         flag = 0         print("Valid Password")         break  if flag == -1:     print("Not a Valid Password ") 

Output
Valid Password

Time complexity: O(n), where n is the length of the password string.
Auxiliary space: O(1), as we are using only a few variables to store intermediate results.

Way 2: 

Python
l, u, p, d = 0, 0, 0, 0 s = "R@m@_f0rtu9e$" if (len(s) >= 8):     for i in s:          # counting lowercase alphabets          if (i.islower()):             l+=1                      # counting uppercase alphabets         if (i.isupper()):             u+=1                      # counting digits         if (i.isdigit()):             d+=1                      # counting the mentioned special characters         if(i=='@'or i=='$' or i=='_'):             p+=1            if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)):     print("Valid Password") else:     print("Invalid Password") 

Output
Valid Password

Time complexity: O(n) where n is the length of the input string s. 
Auxiliary space: O(1) as it only uses a few variables to store the count of various characters.

Way 3: Without using any built-in method

Python
l, u, p, d = 0, 0, 0, 0 s = "R@m@_f0rtu9e$" capitalalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ" smallalphabets="abcdefghijklmnopqrstuvwxyz" specialchar="$@_" digits="0123456789" if (len(s) >= 8):     for i in s:          # counting lowercase alphabets         if (i in smallalphabets):             l+=1                      # counting uppercase alphabets         if (i in capitalalphabets):             u+=1                      # counting digits         if (i in digits):             d+=1                      # counting the mentioned special characters         if(i in specialchar):             p+=1         if (l>=1 and u>=1 and p>=1 and d>=1 and l+p+u+d==len(s)):     print("Valid Password") else:     print("Invalid Password") 

Output
Valid Password

Time complexity : O(n), where n is the length of the input string s. 
Auxiliary space : O(1), as here only few variables are used to store the intermediate results. 



Next Article
Strong Password Suggester Program
author
chinmoy lenka
Improve
Article Tags :
  • Python
  • Python Programs
  • Python Regex-programs
  • Python string-programs
  • python-regex
  • python-string
Practice Tags :
  • python

Similar Reads

  • Strong Random Password Generator Online
    This Strong Random Password Generator offers an invaluable understanding of the significance of strong passwords and provides strong Passwords with the power of a reliable password generator tool. This tool Allows users to define password length, and character types (uppercase, lowercase, numbers, s
    3 min read
  • Tips For Choosing a Strong Password
    Forgot your password?... Let’s reset with the whole concept. So what is your Password? PassWord PassssWord1 Paasword9876… or Names of favorite sports personalities, celebs, and even brands are used as passwords by so many people. And then random posts, messages, and comments from your account, getti
    5 min read
  • 5 Most Popular Methods Used By Hackers To Crack Password
    In today's world, almost еvеryonе has bank accounts, еmail and social mеdia accounts that rеquirе passwords to accеss. Howеvеr, many pеoplе еithеr storе thеir passwords on thе dеvicе or choosе wеak passwords that can bе еasily guеssеd. Hackеrs arе always trying to stеal passwords that give thеm acce
    6 min read
  • How to Remove Windows 10 Password?
    Looking to remove your Windows 10 password for a faster login experience? Whether you want to disable the password on Windows 10 or simply streamline the login process, this guide will walk you through the steps to turn off the Windows 10 login password. By following these easy steps, you'll learn h
    4 min read
  • How to Recover an Apple ID Password?
    Forgetting your Apple ID password can be a frustrating experience for users, especially considering how integral the Apple ID is to accessing various services like iCloud, the App Store, and Apple Music. Fortunately, recovering your Apple ID password is a straightforward process. This article will w
    6 min read
  • How to Change Computer Password?
    There are only a few people who don't use passwords on their Computer. User password is the most basic security check that helps you restrict unauthorized access to your computer. It's a good practice to change your passwords in a short span that helps your password to be healthy. By the end of this
    3 min read
  • Random password generator in C
    In this article, we will discuss how to generate a random password of a given length consists of any characters. Approach: The below-given program involves basic concepts like variables, data types, array, loop, etc.Follow the below steps to solve this problem:Take the length of the password and dec
    2 min read
  • Generating Strong Password using Python
    Having a weak password is not good for a system that demands high confidentiality and security of user credentials. It turns out that people find it difficult to make up a strong password that is strong enough to prevent unauthorized users from memorizing it. This article uses a mixture of numbers,
    3 min read
  • Create a Password Strength Checker using HTML CSS JS
    This project aims to create a password strength checker using HTML, CSS, and JavaScript that is going to be responsible for checking the strength of a password for the user's understanding of their password strength by considering the length of the password which will be that the password should con
    3 min read
  • Program to check Strength of Password
    A password is said to be strong if it satisfies the following criteria: It contains at least one lowercase English character.It contains at least one uppercase English character.It contains at least one special character. The special characters are: !@#$%^&*()-+Its length is at least 8.It contai
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences