Пользовательский ввод проверки не будет придерживаться - PullRequest
0 голосов
/ 29 февраля 2020

Сначала я хочу поблагодарить всех и каждого за то, что они нашли время, чтобы помочь скрабу, как я, и ценить ваше время, помогая мне. Поэтому я пытаюсь сделать простой сценарий создания пользователя. Запрашивая у пользователя его имя и фамилию, объединяет первую букву имени пользователя с фамилией и объединяет ее со случайным числом для создания имени пользователя. Затем я предложу пользователю создать пароль, длина которого должна быть не менее 6 символов. После этого я прошу пользователя подтвердить свой пароль. Я схожу с ума, потому что, когда программа достигает шага проверки пароля, она не проверяет 6 символов и не проверяет, совпадают ли пароли, и переходит к остальной части программы.

Это фрагмент части пароля:

# Ask the user for a password that's at least 6 characters long

 while True:
    password = input("Enter a password for this account: ")
# Verify that the user's input is 6 characters long

    if len(password) < 6:
        print("Your password must be at least 6 characters long! ")
# Has the user verify the password

    password = input("Please verify your password by typing it in again: ")
    if password == password:
        print("Thank you for confirming your password")
    else:
        print("Nope your password did not match")

И после всего этого у меня есть логин пользователя с новой сгенерированной информацией. Используя имя пользователя, сгенерированное в первой части, и пароль, который они вводят во второй части, и проверяя. То же самое, он пропускает проверку и продолжает работу с программой. Я схожу с ума, потому что я потратил пару часов, просто изучая некоторые основы, поскольку я начинающий с python.

Вот полный код:

def main():
print("You do the typin, I will take care of the rest!")

#User will be prompted to input their first and last name
firstname = input("Please give me your first name. ")
lastname = input("Thank you, now please give me your last name. ")

# The first and last name will be concatenated and the first letter of the
# users name will be attatched to their last name.

username = firstname[0] + lastname[:7]

# Now to generate the random number from 100-999 to attach to the new
# username

import random
from random import randint

print("Welcome", username + str(random.randint(100,999)))

import re

def sub():

# Ask the user for a password that's at least 6 charcaters long
 while True:
    password = input("Enter a password for this account: ")
# Verify that the users input is 6 charcters long
    if len(password) < 6:
        print("Your password must be at least 6 charcaters long! ")
# Has the user verify the password
    password = input("Please verify your password by typing it in again: ")
    if password == password:
        print("Thank you for confirming your password")
    else:
        print("Nope your password did not match")
# Now the user must login using the generated username from above
    username = input("Enter your generated username! ")
    if username == username:
        print("Correct!")
    else:
        print("I have never seen you before!")
    password = input("Now enter your accounts password: ")
    if password == password:
        print("You are now logged in!")
    else:
        print("FAIL")
    break
main()
sub()

1 Ответ

0 голосов
/ 29 февраля 2020

Итак, в вашем коде много ошибок. Во-первых, ничто не мешает программе прогрессировать, если пароль меньше 6 символов. Во-вторых, password == password ВСЕГДА вернет true, потому что вы проверяете переменную против себя. Я переписал немного вашего кода, чтобы попытаться прояснить вашу проблему. Надеюсь, это поможет! Я также разделил код на несколько функций + добавлен getpass (https://docs.python.org/3/library/getpass.html)

from getpass import getpass # You can use this module to hide the password the user inputs
from random import randint

def generate_username():
    # Basic username generation, same thing you did
    print("You do the typin, I will take care of the rest!")
    firstname = input("Please give me your first name. ")
    lastname = input("Thank you, now please give me your last name. ")
    username = firstname[0] + lastname[:7] + str(randint(1, 99))
    # You can't concatenate strings and ints, so I convert the number to a string first
    print(f"Your username is: {username}") # f-strings (https://realpython.com/python-f-strings/)
    return username



def generate_password():
    while True:
        password = getpass("Enter a password for this account: ")
        confirm_password = getpass("Enter your password again: ") # Ask the user to enter the password a second time to confirm
        if password != confirm_password: # Check if the user entered the same password
            print("Passwords dont match!")
        elif len(password) < 6: # Check the length
            print("Your password must be at least 6 charcaters long! ")
        else: # If everythings all good
            print("Password is valid!")
            return password # Break the loop and return password value

def login(username, password):
    # Used to login a user
    while True:
        entered_username = input("Enter your username: ")
        entered_password = getpass("Enter your password: ")
        if username == entered_username and password == entered_password:
            # Confirm if username and password are correct, then exit the loop (or do something else)
            print("Login successful!")
            break
        else:
            print("Login failed, please confirm your username and password")

username = generate_username()
password = generate_password()
login(username, password)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...