Int is not subscriptable [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to make a password system is python but when I tried to compere the user password to the right password I get an exception
'int' object is not subscriptable
import time
user_pass = input("Enter password here: ")
if len(user_pass) == 4:
print("u entered the correct amount of numbers!"), time.sleep(0.5)
else:
print("wrong password!")
exit()
for i in user_pass:
if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
password = 1234
if (user_pass[0]) == str(password[0]):
print("the first number is correct")
else:
print("the first number is wrong!")
exit()

A couple of things here;
Firstly you need to indent your if not i.isdigit() block:
if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
You will probably get an exception otherwise.
For your issue; it looks like you are setting the value of password = 1234 which is a integer. You can set this to password="1234" or str(password)[0].

the error occurs because in the line (user_pass[0]) == str(password[0]) you are trying to take the first character in an integer value, you can do this only with strings, so to fix your problem you should modify this (user_pass[0]) == str(password[0]) to this: str(user_pass)[0] == str(password)[0]
so the script should look like this:
import time
user_pass = input("Enter password here: ")
if len(user_pass) == 4:
print("u entered the correct amount of numbers!")
time.sleep(0.5)
else:
print("wrong password!")
exit()
for i in user_pass:
if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
password = 1234
if str(user_pass)[0] == str(password)[0]:
print("the first number is correct")
else:
print("the first number is wrong!")
exit()

I've tested your code and formatted it again. there was some minor issue regarding indent and string casting, check this out
import time
user_pass = input("Enter password here: ")
if len(user_pass) == 4:
print("u entered the correct amount of numbers!"), time.sleep(0.5)
else:
print("wrong password!")
exit()
for i in user_pass:
if not i.isdigit():
print("u must enter numbers only! \"{}\" is not a number!!!!!!!".format(i))
exit()
password = "1234"
if (user_pass[0]) == password):
print("the first number is correct")
else:
print("the first number is wrong!")
exit()

Related

Create a python file that asks user 4 digit pin [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have an assignment where I have to ask the user for a 4 digit pin. The correct pin is 1234. I have to give the user 3 times before they're locked out. I also have to add a break statement. This is the example of the output:
Please enter your pin code: 1112
Incorrect. Please enter again: 1112
Incorrect. Please enter again: 1234
Correct.
My code:
def verify_pin(pin)
if pin == "1234"
return True
else:
return False
tries = 3
while counter < 3:
pin = input("please enter your pin code")
if verify_pin(pin)
print("Correct")
break
elif
print("Incorrect.Please enter again: ")
tries +=1
I received an invalid syntax. I don't know what I am doing at all but I really want to understand and learn. Please help.
You are sort of close, but you have some issues with the code (mainly indentation issues, as mentioned in comments). Something like this should work though:
desired_pin = '1234'
max_tries = 3
def verify_pin(the_pin):
return the_pin == desired_pin
def main():
tries = 0
while tries < max_tries:
pin = input('please enter your pin code: ')
if verify_pin(pin):
print('Correct')
break
else:
print('Incorrect. Please enter again: ')
tries += 1
else: # Else will run when no `break` statement is run in while loop.
print("I am LOCKIN' you out now!")
if __name__ == '__main__':
main()
Sample interaction:
please enter your pin code: 111
Incorrect. Please enter again:
please enter your pin code: 222
Incorrect. Please enter again:
please enter your pin code: 123
Incorrect. Please enter again:
I am LOCKIN' you out now!
You have made some indentation and syntax errors. I have made some changes, please compare this with your code and you can understand the difference
def verify_pin(pin):
if pin == "1234":
return True
else:
return False
tries = 0
while tries < 3:
pin = input("please enter your pin code")
if verify_pin(pin):
print("Correct")
break
else:
print("Incorrect.Please enter again: ")
tries +=1
You are having syntax & indent issues kindly check the below code
def verify_pin(pin):
if pin == "1234":
return True
else:
return False
tries = 0
while tries < 3:
pin = input("please enter your pin code")
if verify_pin(pin):
print("Correct")
break
else:
print("Incorrect.Please enter again: ")
at = 2 - tries
print("You Have %s More Attempt Remaining" % at)
tries += 1

Python - Issue trying to get user input to convert to string and to prevent the user from entering in non decimal numbers [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Complete Python novice here working on a project we have been set to complete. I want the user to input a integer, which they can, I also want the program to not allow non int input into this. I tried mixing some things I found online, but seem to have broken my code and now I'm not sure why. Here is the code:
student_list = []
def student_data():
while True:
student_name = input("Hello, please enter the student name, press 'q' to quit this program:")
if str.lower(student_name) == "q":
break
student_list.append(student_name)
for student_name in student_list:
print("You entered:", student_name)
while True:
grade = (input("Please enter the student grade, enter 'q' to quit this program:"))
if str.lower(grade) == 'q':
return None
while True
try:
student_grade = int(grade)
return student_grade
except ValueError:
print("Please enter a grade between 1-10")
student_list.append(grade)
return student_data()
for student_grade in student_list:
print("You entered:", student_grade)
student_data()
print(student_list)
The previous code had this below but a string input would break the int(input), the goal is to make an input system that puts both the student name and grade into a list, then that list will go into a master list so groupings can be stored.
student_list = []
def student_data():
while True:
student_name = input("Hello, please enter the student name, press 'q' to quit this program:")
if str.lower(student_name) == "q":
break
student_list.append(student_name)
for student_name in student_list:
print("You entered:", student_name)
while True:
grade = int(input("Please enter the student grade, enter '11' to quit this program:"))
if grade >= 11:
break
student_list.append(grade)
for grade in student_list:
print("You entered:", grade)
student_data()
print(student_list)
: is missing after the third while statement, also except and print statements have the same indentation level.
You can use try-except without additional while loop, check if the input number is less then 11 and append the input the the list and if not break the while loop.
Example:
while True:
try:
grade = int(input("Please enter the student grade, enter '11' to quit this program:"))
if grade >= 11:
break
student_list.append(grade)
except ValueError:
print("Please input integer between 1-10")
flows answered your question appropriately.
Because I think you would like to ask for pairs of name and grade, I modified your program a little.
def student_data():
student_list = []
while True:
# Ask for the name of the student
student_name = input("Please enter the student name, press 'q' to quit this program: ")
# When "q" is entered exit the loop.
if student_name.lower() == 'q':
break
# Keep asking about the student's grade until a valid answer has been entered.
while True:
try:
student_grade = int(input("Please enter a grade between 1-10: "))
# If an error occurs during the conversion, the following lines
# are not executed. A direct jump is made to the except block.
if 0 < student_grade <= 10:
# If the value is within the expected limits add a tuple of
# name and grade to the list and exit the nested loop.
student_list.append((student_name, student_grade))
break
except ValueError:
# Ignore errors when converting the string to integer.
pass
# Return all pairs of name and grade as the result of the function.
return student_list
for name, grade in student_data():
print('You entered: ', name, grade)

Trying to create program that exits after 6 incorrect attempts at entering username and password

In the beginning stages of learning Python and I've hit a bit of a snag
I'm trying to create a program that asks for a specific username and password. After 6 incorrect attempts, it will quit the program. Sample code works fine when I put in the correct info. The issue I'm having is when the username is correct but the password is not. I want it to print that the "password doesn't match" and re-ask for the password. It takes me back to the beginning of the program and asks for my username again. Any ideas to solve this? Thank you in advance!
Code can also be found here: https://pastebin.com/4wSgB0we
import sys
incorrect = 0
max_tries = 6
choices = ['Drake', 'swordfish']
run = True
while run:
while incorrect < max_tries:
user_input = input('Please enter username: ')
if user_input not in choices:
incorrect += 1
print(f"{user_input} is incorrect. Please try again.")
else:
print(f"Welcome back {user_input}.")
pass_input = input('Please enter password: ')
if pass_input not in choices:
incorrect += 1
print("Password does not match. Please try again")
else:
run = False
print('Access granted')
sys.exit()
if incorrect == max_tries:
sys.exit()
If it didn't help you solve the problem.
I will modify.
When your user is correct, you should leave While.
If you do not leave While, the user account will be asked again.
while run:
while incorrect < max_tries:
user_input = input('Please enter username: ')
if user_input not in choices:
incorrect += 1
print(f"{user_input} is incorrect. Please try again.")
else:
print(f"Welcome back {user_input}.")
break
while incorrect < max_tries:
pass_input = input('Please enter password: ')
if pass_input not in choices:
incorrect += 1
print("Password does not match. Please try again")
else:
run = False
print('Access granted')
sys.exit()
if incorrect == max_tries:
sys.exit()

How to I repeat code until certain condition is met? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm very new at Python, and I'm trying to make a simple program that asks the user for a password, and if the user didn't guess the password they were asked, ask again until they guess it. How do I do that?
Password = input("guess the password: ")
while (password) != "12345":
Print(input("try again : "))
Welcome to Programming and StackOverflow. Have a look a this Example,
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
The break statement ends the while loop.
#g23's Answer is more apt in the context of the question
Make sure your capitalization is right, generally variables are lowercase, but you need to be consistent.
Also when you ask for the password again, you need to store what the user gives you so it can be checked in the loop condition (the while password != "12345": part)
Something like
password = input("Enter the password: ")
while password != "12345":
password = input("try again: ")
This code does what you want. It has a while loop to check if the password was guessed until the right password is entered. Then it has an if statement to write a message: if the right password is entered, it writes it.
password = input("Enter the password: ")
while password != "12345":
password = input("try again: ")
if password == "12345":
print("Correct password!")

welcome. denied!!! press enter to quit [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I tried to create a username and password program for my family, but when I open it it says:
Welcome.
Denied!!!
Press enter to quit.
Can anyone solve my problem? The code is below:
print ("Welcome.")
username = ("Please enter your username.")
if username == ("mom, savanna, joseph"):
print ("Granted.")
password = input ("Please enter your password.")
if password == ("1975, 2000, jesus"):
print ("Granted.")
question = ("Do you like it?")
if question == ("yes"):
print ("I thought you would.")
if question == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
else:
print ("Denied!!!")
input ("press enter to quit")
Your primary issue is on this line:
username = ("Please enter your username.")
I presume you mean to have an input function call there.
username = input("Please enter your username.")
That will solve your immediate rejection issue.
You also have the same issue on this line:
question = ("Do you like it?")
Which should also be:
question = input("Do you like it?")
Here's the thing:
You are new to code. We can see that here. However, there is always room for improvement and you can learn from mistakes. Some people make odd code sometimes ;)
I have created a working model for you to see where you went wrong.
print ("Welcome.")
username = input("Please enter your username.")
if username in ("mom", "savanna", "joseph"):
password = input("Please enter your password.")
if password in ("1975","2000","jesus"):
print ("Granted.")
question = input("Do you like it?")
if question == ("yes"):
print ("I thought you would.")
elif question == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
break
You typed question = ("Do you like it?") without the input. This is important since it actually lets the user type something.
You wrote if username == ("mom,savanna,joseph")
this means that if the username is mom,savanna,joseph then you get in. obviously you wanted only one of these to get in. the Boolean operator or can help a lot in this situation.
Notice how I used elif instead of if. Python can only have one if and one else. but as many elifs as you want. It means else-if.
EDIT:
After reading Joel's comment, I noticed that you probably want Mom's password to be 1975, Savannah's to be 2000, and Joseph's to be jesus. How do you think you can do that by using my code given here?
I'm assuming you want to have 3 different usernames, and mom's password to be 1975 etc.
password = {"mom":"1975", "savanna":"2000", "joseph":"jesus"}
print ("Welcome.")
username = input("Please enter your username.")
if username in password: #if x in dict returns True if dict has the key x
print ("Granted.")
mypassword = input ("Please enter your password.")
if mypassword == password[username]:
print ("Granted.")
answer = input("Do you like it?")
if answer == ("yes"):
print ("I thought you would.")
elif answer == ("no"):
print ("I guess I could do better")
else:
print ("error")
else:
print ("Denied!!!")
else:
print ("Denied!!!")
input("press enter to quit")
You may want to put a loop around it so that it doesn't have to get restarted if there's a bad entry.
you are asking if username == ("mom, savanna, joseph") instead of if username in ("mom, savanna, joseph")
if you entered in "mom" for username when it asked you, it would be like comparing this
if "mom" == ("mom, savanna, joseph"):
("mom, savanna, joseph") and "mom" are not equal
to check if an item is in a list use the in keyword
>>> x = [0, 1, 2, 3, 4]
>>> 3 in x
True
you also did the same thing when checking if password ==
also #Alexander O'Mara is correct, you never did the input() for username

Categories