how to assign multiple string values to a variable in python - python

I am new to python, just start learning :P
I am trying to create a password protected program, but I am stuck in assigning multiple string values to single variable.
can anyone help me solving this problem,
If you guys have better idea for this "login type" program please guide me !
I want to assign all different possible synonyms assign to one variable so it become easy for user to enter!!!
(my English :P)
#Code 1
User_Name = "Allex_Benzz", "allex benzz", "allex_benzz", "Allex Benzz"
User_Input = input("Please Input Your User Name...!\n")
if User_Input == User_Name:
User_Password = "0011"
User_Input_Password = input("Please Enter Your Password...!\n")
if User_Input_Password == User_Password:
print("Welcome Allex Benzz")
else:
print("Your Password Is Incorrect..!")
else:
print("No Users Found")
Result Code 1
Please Input Your User Name...!
allex benzz #(User Input)
No Users Found
#Python login
#Code 2
User_Name = "Allex_Benzz"
User_Name = "allex benzz"
User_Name = "allex_benzz"
User_Name = "Allex Benzz"
User_Input = input("Please Input Your User Name...!\n")
if User_Input == User_Name:
User_Password = "0011"
User_Input_Password = input("Please Enter Your Password...!\n")
if User_Input_Password == User_Password:
print("Welcome Allex Benzz")
else:
print("Your Password Is Incorrect..!")
else:
print("No Users Found")
#Result Code 2
#In this case its is only working if I use Allex Benzz because User_Name is setted to Allex Benzz
Please Input Your User Name...!
allex benzz #User_Input
No Users Found
#working Result for Code 2
Please Input Your User Name...!
Allex Benzz #User_Input
Please Enter Your Password...!
0011 #User_Password
Welcome Allex Benzz

In this code:
User_Name = "Allex_Benzz", "allex benzz", "allex_benzz", "Allex Benzz"
User_Input = input("Please Input Your User Name...!\n")
if User_Input == User_Name:
# ...
User_Name is a tuple of multiple strings, and User_Input is a single string. A single string will never be equal to (==) a tuple, but it can be in a tuple. Change the if check to:
if User_Input in User_Name:
and it should work the way you intend.

Related

User input validation will not stick

I first want to thank anyone and everyone in advance for taking the time to help a scrub like me and appreciate your time in giving me a helping hand. So I am attempting to make a simple user creation script. Asking the user for their first and last name, concatenated the user's first letter of their first name with their last and concatenating it with a random number to create their user name. I then will prompt the user to create a password and have the password be a minimum of 6 characters long. After that, I ask the user to verify their password. I've been going crazy because when the program reaches the password verification step, it doesn't check for the 6 characters or verify that the passwords are the same and continues to the rest of the program.
This is a snippet of the password part:
# 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")
And after all of that, I am having the "user" login with the new information that was generated. Using the username generated in the first part and using the password they input in the second and checking. The same thing, it skips the check and continues with the program. I am going insane because I've spent a couple of hours just learning some basics as I am a beginner with python.
Here is the full code:
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()
So, there are many errors in your code. The first one is, there's nothing that stops the program from progressing if the password is less than 6 characters. Second, password == password will ALWAYS return true, because you're checking a var against itself. I re-wrote a bit of your code to try to help clarify your problem. I hope this helps! I also split the code into a few functions + added 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)

infinite while loop in last lines of code

Could anyone please assist me with the following:
I have a code that reads a username and password then allows users to access a program. I have the first option to register a new user correct. I'm having a problem with an infinite loop problem with my last two lines of code. Id like to run a string stating that if an unregistered username is entered it returns with a string saying that there is no such registered user. The string just keeps running in the loop and is there anything I could do to change this.
username: admin
password: adm1n
my code is as follows:
users = {}
with open ('user.txt', 'rt')as username:
for line in username:
username, password = line.split(",")
users[username.strip()] = password.strip() # strip removes leading/trailing whitespaces
uinput = input("Please enter your username:\n")
while uinput not in users:
print("Username incorrect.")
uinput = input("Please enter a valid username:/n")
if uinput in users:
print ("Username correct")
with open('user.txt', 'rt') as password:
for line in password:
username, password = line.split(",")
users[password.strip()] = username.strip() # strip removes leading/trailing whitespaces
uinput2 = input("Please enter your password:\n")
while uinput2 not in users:
print("Your username is correct but your password is incorrect.")
uinput2 = input("Please enter a valid password:\n")
if uinput2 in users:
password2 = ("Password correct")
print (password2)
if password2 == ("Password correct"):
menu = (input("\nPlease select one of the following options:\nr - register user\na - add task\nva - view all tasks\nvm - view my tasks\ne - exit\n"))
if menu == "r" or menu == "R":
new_user = (input("Please enter a new user name:\n"))
new_password = (input("Please enter a new password:\n"))
with open ('user.txt', 'a')as username:
username.write("\n" + new_user + ", " + new_password)
elif menu == "a" or menu == "A":
task = input("Please enter the username of the person the task is asigned to.\n")
while task not in username:
print("User not registered. Please enter a valid username:\n")
You have a loop at the end that says
while task not in username:
print("User not registered. Please enter a valid username:\n")
This is unfinished and will loop endlessly since if task is not in username, printing something will not change that fact so it will just loop and print again. You probably wanted to add something like
task = input("Please enter a valid username of a person the task is assigned to.\n")

Confirm user and password from a list of class objects

I need to be able to validate the user and the password inputted, but when I run the code below, I'm able to verify only the first element of the list and the second element and so on aren't being verified.
Note: The user and password are stored in the list as class objects [like this:
admin(user, password)]...
def login(self):
user_name = input("Please Enter Your Username : ").upper()
password = input("Please Enter Your Password : ").upper()
for obj in self.admins:
while obj.admin_name != user_name and obj.admin_password != password:
print(" Sorry Username and Password Incorrect Please Re-enter for Validation ")
user_name = input("Please Enter Your Username : ").upper()
password = input("Please Enter Your Password : ").upper()
else:
print("Greetings,", user_name, "You are Now Logged in the System")
break
When you run break in your else branch you are actually calling it on the for loop. Remove the break and it should be working as you expect it to
Your while loop only checks for the first user name. You should switch the order of your loops:
def login(self):
user_name = input("Please Enter Your Username : ").upper()
password = input("Please Enter Your Password : ").upper()
while True:
for obj in self.admins:
if obj.admin_name == user_name and obj.admin_password == password:
break
else:
print(" Sorry Username and Password Incorrect Please Re-enter for Validation ")
user_name = input("Please Enter Your Username : ").upper()
password = input("Please Enter Your Password : ").upper()
continue
break
print("Greetings,", user_name, "You are Now Logged in the System")
This is also a very bad way to check passwords.
Simply remove break from your else statement.

Python login check auths any correct letter

The issue I keep having is that after I register a username/password, then try to login if I get any letters or numbers of the login/password correct it accepts it, for example if my username is Fof and my Password is tog and I enter the username as just f or o it will accept it.
Here's the code written in Python idle 3.7:
if Game == "1":
username = input("Please enter your username: ")
if username in open("Names.txt").read(): #fix
print ("Welcome " + username)
password = input("Please enter your password: ")
if password in open("Passwords.txt").read():
print ("success!")
else:
print("Username incorrect!")
An explanation of what you need:
You need to look for the exact match of the word in the file, not just in because that would always return True and hence it would bypass:
An example:
NamesList:
Fof
Abc
Def
and then:
import re
text = input("enter Name to be searched:")
NamesFile = open("NamesList.txt", "r")
for line in NamesFile:
if re.search(r"\b" + text + r"\b", line):
print(line)
else:
print("Name not found")
break
OUTPUT:
enter Name to be searched:Fof
Fof
In another case:
enter Name to be searched:f
Name not found
If you store logins and passwords the way you do, then one user can use password of another user and vice versa. It's better to store login-password pair together:
File credentials.json:
{"Fof": "tog"}
Code:
import json
with open('credentials.json') as f:
credentials = json.load(f)
username = input('Please enter your username: ')
if credentials.get(username):
print('Welcome {}'.format(username))
password = input('Please enter your password: ')
if credentials[username] == password:
print('success!')
else:
print('Username incorrect!')
Let's try to hack:
Please enter your username: f
Username incorrect!
Successful login:
Please enter your username: Fof
Welcome Fof
Please enter your password: tog
success!

Why is my password programme code not working?

The code will only let me guess once . Can someone please tell me what is wrong with my code?
Challenge:
Write a program that sets a password as ‘Gain Access ’ and asks the
user to enter the password and keeps asking until the correct password
is entered and then says ‘Accepted’. The program should count how many
attempts the user has taken and tell them after they have been
accepted.
enter code here
password = 'Gain access'
count = 0
input = input("Enter the password: \n")
while input != password:
print("Incorrect password! Please try again: \n")
count = count + 1
print("You have now got your password wrong " + str(count) + " times. \n")
if(count < 5):
print("Access denied, please contact security to reset your password.")
break
else:
print("Accepted, welcome back.")
print("You had " + str(count) + " attempts until you got your password right.")
You should always include the language you're programming in like simonwo mentioned already.
Looks like Python to me though. I suppose this line input = input("Enter the password: \n") needs to go after while input != password:, as well. Otherwise you can only enter the password once and then it directly executes all 5 loops. But you should NOT assign input because this is the function you want to obtain the input from.
Do something like user_input = input("Enter the password: \n"). So your code should look something like this:
...
user_input = input("Enter the password: \n")
while user_input != password:
print("Incorrect password! Please try again: \n")
user_input = input("Enter the password: \n")
... Your existing code here
But note that this way the user won't get notified if they entered the correct password with their first try. You could insert a check after the first reading of the user input and if it matches the desired password print your welcome phrase.

Categories

Resources