Python if error password

Проверка пароля

Как известно, когда мы придумываем пароль от аккаунта ВКонтакте, электронной почты или Яндекс.Контеста, к этому паролю часто предъявляются определённые требования по сложности.

Напишите программу, которая имитирует проверку пароля, придуманного пользователем. Пользователь вводит пару слов: пароль, а потом ещё раз его же, для подтверждения.

Если введённая пара не удовлетворяет одному из перечисленных ниже условий, пользователь вводит пару паролей ещё раз, и так до тех пор, пока не будут выполнены все условия (т. е. пока программа не выведет «OK»).

если первый пароль из пары, который ввёл пользователь короче 8 символов, программа выводит на экран слово «Короткий!» и заново считывает пару слов-паролей;
если же первый пароль из пары достаточно длинный, но в нём содержится сочетание символов «123», программа выводит на экран слово «Простой!» и снова читает пару слов-паролей;
если же предыдущие проверки пройдены успешно, но введённые слова-пароли не совпадают, то программа выводит на экран слово «Различаются.» и опять же читает пару слов-паролей;
если же и третья проверка пройдена успешно, программа выводит «OK» (латинскими буквами) и заканчивает свою работу.
Формат ввода
Несколько раз подряд следуют две строки — пароль, введённый пользователем в первый и во второй раз.

Формат вывода
Несколько строк — результат проверки пар паролей.

У меня код пишет ошибку,хз почему

1 2 3 4 5 6 7 8 9 10 11 12 13
while True: a = input().split(maxsplit=1) if len(a)  2: else: if len(a[0])  8: print('Короткий!') elif '123' in a[0]: print('Простой!') elif a[0] != a[1]: print('Различаются.') else: break print('OK')

Ошибка:
Лог компиляции
stdout:
/bin/sh ./build.sh 1>&2
Makefile:2: recipe for target ‘build’ failed

stderr:
./solution.py:4:1: E112 expected an indented block
./solution.py:4:1: E999 IndentationError: expected an indented block
Код не соответствует стандарту PEP8
make: *** [build] Error 1

Источник

Python if error password

Let’s take a password as a combination of alphanumeric characters along with special characters, and check whether the password is valid or not with the help of few conditions. Conditions for a valid password are:

  1. Should have at least one number.
  2. Should have at least one uppercase and one lowercase character.
  3. Should have at least one special symbol.
  4. Should be between 6 to 20 characters long.
Input : Geek12# Output : Password is valid. Input : asd123 Output : Invalid Password !!

We can check if a given string is eligible to be a password or not using multiple ways. Method #1: Naive Method (Without using Regex).

Python3

print ( ‘length should be at least 6’ )

print ( ‘length should be not be greater than 8’ )

if not any (char.isdigit() for char in passwd):

print ( ‘Password should have at least one numeral’ )

if not any (char.isupper() for char in passwd):

print ( ‘Password should have at least one uppercase letter’ )

if not any (char.islower() for char in passwd):

print ( ‘Password should have at least one lowercase letter’ )

if not any (char in SpecialSym for char in passwd):

print ( ‘Password should have at least one of the symbols $@#’ )

This code used boolean functions to check if all the conditions were satisfied or not. We see that though the complexity of the code is basic, the length is considerable. Method #2: Using regex compile() method of Regex module makes a Regex object, making it possible to execute regex functions onto the pat variable. Then we check if the pattern defined by pat is followed by the input string passwd. If so, the search method returns true, which would allow the password to be valid.

Python3

Using ascii values and for loop:

This code uses a function that checks if a given password satisfies certain conditions. It uses a single for loop to iterate through the characters in the password string, and checks if the password contains at least one digit, one uppercase letter, one lowercase letter, and one special symbol from a predefined list and based on ascii values. It sets a boolean variable “val” to True if all these conditions are satisfied, and returns “val” at the end of the function.

The time complexity of this code is O(n), where n is the length of the password string. The space complexity is O(1), as the size of the variables used in the function does not depend on the size of the input.

Python3

print ( ‘length should be at least 6’ )

print ( ‘length should be not be greater than 8’ )

if ord (char) > = 48 and ord (char) < = 57 :

elif ord (char) > = 65 and ord (char) < = 90 :

elif ord (char) > = 97 and ord (char) < = 122 :

print ( ‘Password should have at least one numeral’ )

print ( ‘Password should have at least one uppercase letter’ )

print ( ‘Password should have at least one lowercase letter’ )

print ( ‘Password should have at least one of the symbols $@#’ )

print (password_check( ‘Geek12@’ ))

print (password_check( ‘asd123’ ))

print (password_check( ‘HELLOworld’ ))

print (password_check( ‘helloWORLD123@’ ))

print (password_check( ‘HelloWORLD123’ ))

True Password should have at least one uppercase letter Password should have at least one of the symbols $@# False Password should have at least one numeral Password should have at least one of the symbols $@# False True Password should have at least one of the symbols $@# False

You are currently viewing Проверка пароля в Python

Давайте возьмем пароль в виде комбинации буквенно-цифровых символов вместе со специальными символами и проверим, является ли пароль действительным или нет, с помощью нескольких условий.

Условиями для действительного пароля являются:

  1. Должно быть хотя бы одно число.
  2. Должно быть по крайней мере один прописной и один строчный символ.
  3. Должен иметь по крайней мере один специальный символ.
  4. Длина должна составлять от 6 до 20 символов.
Вход : Geek12# Вывод : Password is valid. Вход : asd123 Вывод : Invalid Password !!

Способ № 1: Наивный метод (Без использования Регулярного выражения).

# Password validation in Python # using naive method # Function to validate the password def password_check(passwd): SpecialSym =['$', '@', '#', '%'] val = True if len(passwd) < 6: print('length should be at least 6') val = False if len(passwd) >20: print('length should be not be greater than 8') val = False if not any(char.isdigit() for char in passwd): print('Password should have at least one numeral') val = False if not any(char.isupper() for char in passwd): print('Password should have at least one uppercase letter') val = False if not any(char.islower() for char in passwd): print('Password should have at least one lowercase letter') val = False if not any(char in SpecialSym for char in passwd): print('Password should have at least one of the symbols $@#') val = False if val: return val # Main method def main(): passwd = 'Geek12@' if (password_check(passwd)): print("Password is valid") else: print("Invalid Password !!") # Driver Code if __name__ == '__main__': main() 

Выход:

В этом коде использовались логические функции для проверки того, были ли выполнены все условия или нет. Мы видим, что, хотя сложность кода является базовой, его длина значительна.

Способ № 2: С помощью регулярное выражение

compile() метод модуля регулярных выражений создает объект регулярных выражений, позволяющий выполнять функции регулярных выражений на похлопывать переменная. Затем мы проверяем, соответствует ли шаблон, определенный похлопывать за ним следует строка ввода passwd. Если это так, метод поиска возвращает истинный, что позволит паролю быть действительным.

# importing re library import re def main(): passwd = 'Geek12@' reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*#?&])[A-Za-zd@$!#%*?&]$" # compiling regex pat = re.compile(reg) # searching regex mat = re.search(pat, passwd) # validating conditions if mat: print("Password is valid.") else: print("Password invalid !!") # Driver Code if __name__ == '__main__': main() 

Выход:

Здесь, учитывая пароль, наша задача — убедиться, что этот пароль действителен или нет. Здесь мы используем модуль re, который предоставляет регулярные выражения, а re.search() используется для проверки правильности алфавитов, цифр или специальных символов.

Алгоритм

Step 1: first we take an alphanumeric string as a password. Step 2: first check that this string should minimum 8 characters. Step 3: the alphabets must be between a-z. Step 4: At least one alphabet should be in Uppercase A-Z. Step 5: At least 1 number or digit between 0-9. Step 6: At least 1 character from [_ or @ or $].

Пример кода

# Python program to check valid password import re passw = input("Enter Password ::>") fl = 0 while True: if (len(passw)<8): fl= -1 break elif not re.search("[a-z]", passw): fl = -1 break elif not re.search("[A-Z]", passw): fl = -1 break elif not re.search("1", passw): fl = -1 break elif not re.search("[_@$]", passw): fl = -1 break elif re.search("s", passw): fl = -1 break else: fl = 0 print(" This Is Valid Password") break if fl ==-1: print("Not a Valid Password")

Вывод

Enter Password ::> vbnA@hj9 This Is Valid Password

отвечаю на ваши вопросы. Автор книг и разработчик.

  • 👉 Как объединить два словаря Python?
  • 👉 Как поменять местами две переменные в Python
  • 👉 Как вывести текущую дату и время на Python?

Переработайте предыдущую программу так, чтобы она делала проверку пароля по критериям, возвращала бы ’ok’, если пароль корректен и выбрасывала бы исключения следующих типов, если он ошибочен:
LengthError — если длина пароля меньше 9 символов.
LetterError — если в пароле все символы одного регистра.
DigitError — если в пароле нет ни одной цифры.
SequenceError — если пароль нарушает требование к последовательности из подряд идущих трех символов (указано в предыдущей задаче).
Все исключения должны быть унаследованы от базового — PasswordError.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
def check_password(a): bad_sequence = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm', 'йцукенгшщзхъ', 'фывапролджэё', 'ячсмитьбю'] num = list('1234567890') if len(a)  9: return 'LengthError' if a.islower() or a.isupper(): return 'LetterError' if a.isdigit() or a.isalpha(): return 'error' b = a.lower() for i in bad_sequence: for j in range(len(i) - 2): if i[j: j + 3] in b: return 'SequenceError' for i in num: if i not in a: return 'ok' return 'DigitError'
пример: Ввод: try: print(check_password("G7FgTU0bwТuio")) except Exception as error: print(error.__class__.__name__) Вывод: SequenceError

Источник

Python Exercise: Check the validity of a password

Write a Python program to check the validity of passwords input by users.

  • At least 1 letter between [a-z] and 1 letter between [A-Z].
  • At least 1 number between 8.
  • At least 1 character from [$#@].
  • Minimum length 6 characters.
  • Maximum length 16 characters.

Sample Solution:-

Python Code:

import re p= input("Input your password") x = True while x: if (len(p)12): break elif not re.search("[a-z]",p): break elif not re.search("2",p): break elif not re.search("[A-Z]",p): break elif not re.search("[$#@]",p): break elif re.search("\s",p): break else: print("Valid Password") x=False break if x: print("Not a Valid Password") 

Flowchart: Python: Check the validity of a password

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

How to delete a file or folder?

  • os.remove() removes a file.
  • os.rmdir() removes an empty directory.
  • shutil.rmtree() deletes a directory and all its contents

Path objects from the Python 3.4+ pathlib module also expose these instance methods:

  • pathlib.Path.unlink() removes a file or symbolic link.
  • pathlib.Path.rmdir() removes an empty directory.
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Читайте также:  Constant member function in cpp
Оцените статью