Can't Assign to Literal in Python - python

I'm receiving an error in python that says I, "Can't assign to literal". I was hoping that somebody could help me understand why this is coming up. Here's my code:
# Chapter 3 Challenge part 3
# use the code below and the following
# directions to see if you can solve the problem
# Your Co-Worker has been asked to write a
# 1st time "Log-in" program in which a user has to
# sign in with their user name. If they enter
# the correct id name they need to be asked
# to create their password.
# They were required to make sure the user did
# not leave the username entry blank and must have the
# correct user name or the progam should re-ask
# them to sign in... They cannot figure out what
# to do, so they have called on you to help...
# Here is what they have so far...
# They started their program like this....
# and included some of their documentation.
# Get username, check to see if not empty,
# then verify that username is correct.
# using username "jalesch" as test user.
name = False
while not name:
name = raw_input("Enter your user name: ")
print "Welcome," , name , "you must create a password."
password = False
while not password:
password = raw_input("""Enter a password.
Password must be at least 6 characters in length,
and must include one of these symbols (!, $, ?, &): """)
while len(password) < 6:
for "!" in password or "$" in password or "?" in password or "&" in password:
password = raw_input("""Enter a password.
Password must be at least 6 characters in length,
and must include one of these symbols (!, $, ?, &): """)
print "This has met the requirements."
check = raw_input("Please re-enter your password:")
while check != password:
print "You have entered the wrong password"
check = raw_input("Please re-enter your password:")
print "Welcome to the program!"
# prompt user to create a password that meets the
# following requirements:
# - Must be at least 6 characters in length
# - Must include at least one of these 4 symbols
# - ! $ ? &
# Once the user has entered their password, the program
# must check to see if it meets the requirements.
# If the requirements are not met, it should reask them
# to put in a password that meets the requirements
# until they get it correct.
# Test password is: $program!
# If it meets the requirements then prompt the user
# to re enter the password, and check that the
# first and second entry matches.
# If the 1st and 2nd match. display "Welcome to the program"
# If the 1st and 2nd don't match, re-prompt for the password
# until they get a correct match.
I also believe that the code is malfunctioning when I try to find the special characters, because it is skipping one of the while loops. Any help is appreciated, thanks.

on this line:
for "!" in password or "$" in password or "?" in password or "&" in password:
You probably meant to use if:
if "!" in password or "$" in password or "?" in password or "&" in password:
for x in y iterates over y, assigning each member to x sequentially, running the following indented code in a loop for each member of y. You can't assign a value to "!" because that's a literal character, not a variable.

def get_name(prompt):
while True:
name = raw_input(prompt).strip()
if name:
return name
def get_password(prompt):
while True:
name = raw_input(prompt).strip()
if len(name) >= 6 and (set(name) & set("!$?&")):
return name
name = get_name("Enter your user name: ")
print("Welcome, {}, you must create a password.".format(name))
while True:
print("Now enter a password. It must be at least 6 characters in length, and must include a symbols (!, $, ?, &).")
pass1 = get_password("Enter a password: ")
pass2 = get_password("Please re-enter your password: ")
if pass1 == pass2:
print("Welcome to the program")
break
else:
print("No match! Please try again")

Related

For some reason my python code is skipping a certain part of code (pygame)

Loging in with jack works fine but I cant login with jake even thought he exists in the array. It just skips the whole for loop "for i in storedusername". An help would be grateful.
Here's the code:
import pygame
import sys
import random
storedusername = ["jack","jack","jack","jake","jack","jack","jack",] # The place where the username is stored
storedpass = ["abcde","abcde","abcde","12345","abcde","abcde","abcde",] # The current place where the password is stored
Login = False
def login(): # Function used to login
global Login # Global the logins fucntion
Login = False # Sets Login to false
user = input("Enter Username: ") # User enters the username that they would like to login with
print(user)
for i in storedusername: # Loops through the items in the list
if i == user: # Compares the items in the list with the username that the user has entered
print("user found") # If the user was found then the program will tell the user that
pos = int(storedusername.index(user)) # Finds the position where the username is stored
print(pos)
for j in range(0,10): # Has 10 tries to do this loop
password = input("Enter Password: ") # The user enters the password which they think matches with the username.
#for i in range(0,10):
if password == storedpass[pos]: # Goes to the position where the password matches the username is stored and compares the values.
print("password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
else:
print("Pasword does not match try again") # If the password does not match then the program will notify it.
print("too many attempts close the program") # If there are too many attempts than it will close.
else:
print("not found") # If the username is not found than it will be promted that it is not found.
return Login # Returns login.
login()
You are using the variable i both for outer and inner loop, so it is changed inside.
It must be:
for i in ... :
...
for j in ... :
...
You were right to think that the indentation wasn't correct. As you had it before, if you entered a username not present in the list, you would still be asked for the password ten times for each user in storedusername (a total of 70 times!). Moving the block from for i in range(0,10) one indentation further fixes it.
for i in storedusername: ############ It skips this loop
if i == user:
print("user found")
pos = int(storedusername.index(user))
print(pos) ########### All the way up to here
# >>>> indent here
for i in range(0,10): # Has 10 tries to do this loop
password = input("Enter Password: ") # The user enters the password which they think matches with the username.
#for i in range(0,10):
if password == storedpass[pos]: # Goes to the position where the password matches the username is stored and compares the values.
print("password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
else:
print("Pasword does not match try again") # If the password does not match then the program will notify it.
# >>>>>
print("too many attempts close the program") # If there are too many attempts than it will close.
else:
print("not found") # If the username is not found than it will be promted that it is not found.
You may see that not working because of wrong indentation of that
else:
print(
"Pasword does not match try again") # If the password does not match then the program will notify it.
print(
"too many attempts close the program") # If there are too many attempts than it will close.
block.
Please move it to to left, and it should be better.
That modified version
storedusername = ["jack", "jack", "jack", "jake", "jack", "jack",
"jack", ] # The place where the username is stored
storedpass = ["abcde", "abcde", "abcde", "12345", "abcde", "abcde",
"abcde", ] # The current place where the password is stored
(width, height) = (644, 412)
Login = False
def login(): # Function used to login
global Login # Global the logins fucntion
Login = False # Sets Login to false
user = input(
"Enter Username: ") # User enters the username that they would like to login with
print(user)
for i in storedusername: ############ It skips this loop
if i == user:
print("user found")
pos = int(storedusername.index(user))
print(pos) ########### All the way up to here
for i in range(0, 10): # Has 10 tries to do this loop
password = input(
"Enter Password: ") # The user enters the password which they think matches with the username.
# for i in range(0,10):
if password == storedpass[
pos]: # Goes to the position where the password matches the username is stored and compares the values.
print(
"password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
# --> wrong indentation
else:
print(
"Pasword does not match try again") # If the password does not match then the program will notify it.
print(
"too many attempts close the program") # If there are too many attempts than it will close.
# <-- wrong indentation
else:
print(
"not found") # If the username is not found than it will be promted that it is not found.
return Login # Returns login.
# register()
login()
allows for
Enter Username: jack
jack
user found
0
Enter Password: abde
Pasword does not match try again
Enter Password: abcde
password match username
Process finished with exit code 0
I'm not going to modify the flow of your solution, but I'd suggest to write comments before the line, not in it. Also you should avoid variables shadowing (using the same variable like i in different scopes). The last thing is that you got slightly wrong indent for password checking - it was run even wihtout matched name. I allowed myself to propose version with all these modifiactions. Please take a look on that:
def login():
""" Function used to login"""
# Global the logins fucntion
global Login
Login = False
# User enters the username that they would like to login with
user = input("Enter Username: ")
print(user)
for stored_user_name in stored_user_names:
if stored_user_name == user:
print("user found")
pos = int(stored_user_names.index(user))
# Has 10 tries to do this loop
for try_attempt in range(0, 10):
# The user enters the password which they think matches with the username.
password = input("Enter Password: ")
# Goes to the position where the password matches the username is stored and compares the values.
if password == storedpasswords[pos]:
# Program returns if the username and password match
print("password match username")
Login = True # Turns login to True
return Login # Returnss Login
else:
# If the password does not match then the program will notify it.
print("Password does not match try again")
# If there are too many attempts than it will close.
print("too many attempts close the program")
else:
# If the username is not found than it will be promted that it is not found.
print("not found")
return Login

How can I see if my password variable is within a line so that my code can proceed?

I am creating a password re-setter for school, and i want to check that if the password is within the first line of the text file, then it can say "Okay, choose a new password")
Newpass=""
Network=""
setpass=""
Newpass=""
password=""
def newpass():
Network=open("Userandpass.txt")
lines=Network.readlines()
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password in line:
newpass=input("Okay, choose a new password ")
Network.close()
Network=open("Userandpass.txt","a")
if len(newpass)>= 8 and newpass[0].isalnum()==True and newpass[0].isupper()==True:
print('password change successful')
Network.write("New Password : " + newpass )
Network.close()
break
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
Network=open("Userandpass.txt","w")
Network.write(input("What is your Username")+",")
Network.write(input("Password:")+ ",")
question=input("Do you want to change your password?")
if question=="yes":
Network.close()
newpass()
else:
Network.close()
print("Okay thank you.")
Please help! I have been looking all over here and i can't find a solution
You can try by two things :
lines=Network.read() # change here
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password == lines.split(",")[1]: # change here also
Explanation :
The problem with readlines is o/p as list where read return as string which is better one to use here .
The second thing it returns as a single string ie, combined form of name and password just with ,. So if you split it you will get an list of separated values. Then you can take only password from it and check with input.
In your code you are just checking the input element is just present in that whole string, not checking whether it is same password or not
You said you needed this for school, so i assume it's somewhat urgent:
All the changes i did are minor and i commented what i did and why.
# no need to intialize these variables
#Newpass=""
#Network=""
#setpass=""
#Newpass=""
#password=""
def newpass():
# the with open() construct takes care of closing the file for you and gives you a nice handle for working with the file object.
with open("Userandpass.txt") as Network:
# this reads all filecontents into a list and while doing so strips away any kind of whitespace.
username,current_password=[x.strip() for x in Network.readlines()]
for i in range (3):
password=input("just to confirm it is you, re-enter your old password: ")
if password == current_password:
# communicate the requirements instead of letting potential users run into errors
newpass=input("Okay, choose a new password (must be 8 chars or more, alphanumeric and have it's first letter capitalized.) ")
if len(newpass)>= 8 and newpass.isalnum() and newpass[0].isupper():
with open("Userandpass.txt","a") as Network:
print('password change successful')
Network.write("New Password : " + newpass )
return
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
with open("Userandpass.txt","w") as pwfile:
# separate by newline instead of punctuation => personal preference
pwfile.write(input("What is your Username? ")+"\n")
pwfile.write(input("Password: ")+ "\n")
question=input("Do you want to change your password? (yes/no): ")
if question[0].lower() == 'y':
newpass()
else:
print("Okay thank you.")
# properly terminate
exit(0)
You are missing an 's' in the line
if password in line**s**:
maybe the problem comes from there.

str.isdigit() doesn't seem to be working in python

I'm working on a password checker that checks if the string is a valid password. I have to check if there is at least eight characters, must consist of only letters and digits and the last two characters must be digits.
It all seems to work so far other than the password.isdigit(). sometimes the password comes out valid and sometimes it doesn't. Any suggestions?
# Gets the users password
password = input('Enter a string for password: ')
# Splices the last two characters of the password
lastTwo = password[-2:]
# Checks the password if it is less than 8 characters
while len(password) < 8:
print('The password you entered is too short.')
print()
password = input('Enter a string for password: ')
# Checks the password if it is composed of letters and numbers
while password.isalnum() == False:
print('Your password has special characters not allowed.')
print()
password = input('Enter a string for password: ')
# Checks the spice to verify they are digits
while lastTwo.isdigit() == False:
print('Your last two characters of your password must be digits.')
print()
password = input('Enter a string for password: ')
print('Your password is valid.')
There are a handful of issues with your provided code. Particularly, you only check the subsequent rules while len(password) < 8. If you give it a password of length 10, the rules are never checked. Additionally, you don't update the lastTwo with each new password attempted
One way to fix this would be to replace your several while statements with if...elif..elif...else... wrapped in an overall while statement, as follows:
# Gets the users password
password = input('Enter a string for password: ')
while True:
# Checks the password if it is less than 8 characters
if len(password) < 8:
print('The password you entered is too short.')
# Checks the password if it is composed of letters and numbers
elif not password.isalnum():
print('Your password has special characters not allowed.')
# Checks the spice to verify they are digits
elif not password[:-2].isdigit():
print('Your last two characters of your password must be digits.')
else:
# we only get here when all rules are True
break
print()
password = input('Enter a string for password: ')
print('Your password is valid.')
This should work as you intended it. But while we're at it, why not tell the user every rule their password has broken? From a UI point of view, it helps to keep the user informed.
If we store an information message alongside whether the relevant rule has been met, we can quickly work out all of the rules that have been broken, like so:
valid_password = False
while not valid_password:
# Get a password
password = input('\nEnter a string for password: ')
# applies all checks
checks = {
'- end in two digits': password[-2].isdigit(),
'- not contain any special characters': password.isalnum(),
'- be over 8 characters long': len(password) > 8
}
# if all values in the dictionary are true, the password is valid.
if all(checks.values()):
valid_password = True
# otherwise, return the rules violated
else:
print('This password is not valid. Passwords must:\n{}'.format(
'\n'.join([k for k, v in checks.items() if not v])))
print('Your password is valid.')
You never update your value of lastTwo inside your while loop. Thus imagine if a user first entered a password abc123. Then lastTwo would be calculated as 23.
Now your code would find that the password is too short and prompt the user for a new password. Suppose he enters abcdefgh. This now passes your first and second checks. Notice however that lastTwo is still 23, and thus your third check will incorrectly pass.
You should thus recalculate the value of lastTwo whenever you accept a new password or directly check like this:
while (password[-2:]).isdigit() == False:

Python GCSE homework help - password

For my homework I need to make a user registration system in python. I need to make a password section.
What I am meant to do?.
Here is my code, I can't work out whats wrong:
password = input("Please enter your password: ")
passwordl = len(password)
while passwordl <= 8:
print("password must be more than 8 characters - please try agian")
password = input("Please enter your password: ")
passworda = password.isalpha()
passwordi = password.isdigit()
while passworda != True or passwordi != True:
print("password needs to contain digits and characters - please re-enter")
password = input("Please enter your password: ")
The code is in a function btw.
Thanks
The functions isalpha() and isdigit() return true if all the members in the string are alphanumeric and digits, respectively.
What you need to do instead is to check if any characters in the string have the right properties, for example like this:
passworda = any([x.isalpha() for x in password])
passwordi = any([x.isdigit() for x in password])
Additionally, you need to redo all the checks (both length and character set checks) each time when the password is entered anew.
Instead of following
Password = input("Please enter your password")
In the last while loop with the checks over again you would be better just calling the password function as it's more efficient.

Password Checker loop not working

I have tried to create an app in Python that makes a user create a password and then makes them verify it. Obviously I had to create a loop so that when the user entered an unmatching password they had to try again. I am not very experienced with loops so here is what I got. How do I make this work?
here is the code:
password = raw_input ("Create a password: ")
passwordv = raw_input ("Retype your password: ")
a = ("Passwords don't match! Please try again!: ")
b = ("Congrats, you have created a password")
def password():
if password == passwordv :
print ("Congrats, you have created a password")
else :
print (a)
return password
return passwordv
while password !=passwordv:
print (a)
here is another set of code trying to do the same thing:
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again: ')
if (password == passwordv) :
print ('Password set')
break
Your conditional to test whether the passwords match was included in the loop which checks that they don't match -- so, it never gets run.
Try this instead:
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
while (password != passwordv):
print raw_input('Passwords do not match, try again. ')
password = raw_input('Create a password: ')
passwordv = raw_input('Verify your password: ')
continue
print ('Password set')
Note how only the code that should be run if the passwords don't match is included within the while loop.
What you need here is an "N and a half times loop". To avoid repeating code (guided by the DRY principle) you might consider writing a function to get the passwords. The following might work:
def get_passwords():
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
return password, passwordv
pw1, pw2 = get_passwords()
while pw1 != pw2:
print "Sorry, passwords do not match"
pw1, pw2 = get_passwords()
The loop won't be entered at all if the original passwords match. Otherwise it will repeat until they do.
password=raw_input('Enter password: \t\t\t')
passwordv=raw_input('Enter password again to verify: \t')
if password == passwordv:
print "\ncongratz you have created password"
else:
print "\nPlease try again...!"
while password != passwordv:
password=raw_input("Enter password: \t\t\t")
passwordv=raw_input("Enter password again to verify: \t")
if password == passwordv:
print"\ncongratz you have created password"
else:
print"\nPlease try again...!"
I know this one is long, It is just for basic understanding
The other answers provide the code that will do what you want. I thought that it could be interesting to tell you a little bit more what was wrong with the code you provided because the problem is more about your understanding of how things work.
1st attempt: a variable and a function have the same name
# Here you define your password variable as a string
password = raw_input ("Create a password: ")
[...]
# And then you reassign it here: it contains now the address of that function!
def password():
[...]
# Now you're comparing a function to a string: they'll never be equal
while password !=passwordv:
[...]
This could have been avoided simply by changing the name of your function (which is never called by the way so I'm not sure what you wanted to do but I thought you might find that interesting). Further reading: Python: function and variable with same name
2nd attempt: the values of the variables stay the same
password = raw_input('Create a password: ')
passwordv = raw_input('Veryify your password: ')
# At this point, if the test is true, you'll reach the end of the code without
# displaying the 'Password set' message you wanted
while (password != passwordv):
# This only prints a message
print raw_input('Passwords do not match, try again: ')
# The condition below can never be true: you just tested that they were
# different but did nothing to give them new values!
if (password == passwordv) :
print ('Password set')
break
The way to fix that is what the other answers provide: take your message out of the loop (getting out of the loop means that your condition was met) ; make sure that you do something inside the loop that will assure that the next test will be different from the previous one (otherwise, you will end up testing the same values over and over again) ; to avoid breaking inside the loop, set your values outside the loop, and then get new values inside the loop in case the initial test failed.
Here's an idea:
First define these:
MinPass = 6
MaxPass = 12
Then this:
print ("Now, lets try with a password. Please enter one here")
EnteredPassword = input("Password: ")
while len(EnteredPassword) < MinPass:
print ("That password is too small. Please try again")
EnteredPassword = input("Password: ")
while len(EnteredPassword) > MaxPass:
print ("That password is too long, please try again")
EnteredPassword = input("Password: ")
Hope this helps!

Categories

Resources