I have made a script for checking if a variable is the same as an input variable:
def password():
userPassword = str(input("Type Your Password: "))
if userPassword == storedPassword:
print 'Access Granted'
else:
print 'Access Denied'
password()
However whenever I type a letter for the input, it throws a NameError, but it works fine with numbers.
Error:
Traceback (most recent call last):
File "C:\Users\***\Desktop\Test\Script.py", line 16, in <module>
password()
File "C:\Users\***\Desktop\Test\Script.py", line 9, in password
userPassword = str(input("Type Your Password: "))
File "<string>", line 1, in <module>
NameError: name 'f' is not defined
You need to use raw_input instead of input on python 2.
Using input attempts to evaulate whatever you pass it. In the case of an integer it just resolves to that integer. In the case of a string, it'll attempt to find that variable name and that causes your error.
You can confirm this by typing a 'password' such as password which would have your input call return a reference to your password function.
Conversely, raw_input always returns a string containing the characters your user typed. Judging by your attempt to cast whatever the user types back into a string, this is exactly what you want.
userPassword = raw_input("Type Your Password: ")
For Python 2.7 you need to use raw_input() instead of input(), input() actually evaluates the input as Python code. raw_input() returns the verbatim string entered by the user.
See Python 2.7 getting user input and manipulating as string without quotations
Related
I need help with this code;
input()
print("Created by Mr.StiK")
input()
print('In a dark and creepy cave... You got your consciousness back...')
input()
print("Then you remember... you've no time to waste...")
input()
unit = input("Type the command 'wake' to start your adventure... ").lower()
while unit.lower() == "wake":
if unit.lower() == "wake":
print("And you starts your adventure...")
break
if not unit.lower() == "wake":
print("Sorry, unidentified command. Please type 'wake'")
The error;
When you type the command wrong, it does not say anything, just skips the code.
And when we input nothing, we get nothing.
And then when we say anything, the program crashes, with this;
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
NameError: name 'wake' is not defined
Please I need help with this.
PS: IF YOU CAN ALSO NEED TO RE-WRITE THE CODE WITH A BETTER CODE/ENGINE, PLEASE, IT WILL BE ACCEPTED TOO.
Change your WHILE_LOOP and INPUT to this
while True:
unit = input("Type the command 'wake' to start your adventure... ").lower()
if unit == "wake":
print("And you starts your adventure...")
break
else:
print("Sorry, unidentified command. Please type 'wake'")
there's a function which called getpass which asks you to provide a password inside a input() and then it returns the password.
I'm trying to cast a string as a getpass object. without using an input.
I'm communicating with telethon api
Whenever I try to use anormal string as my password I endup with the message "Couldn't login"
you can view the code here:
try:
obj.client.sign_in(obj.user.phone, code = code)
except SessionPasswordNeededError:
try:
obj.client.sign_in(password=obj.client.cloud)
except:
print("Couldn't log")
But when I use
try:
obj.client.sign_in(obj.user.phone, code = code)
except SessionPasswordNeededError:
try:
passw = getpass.getpass()
obj.client.sign_in(password=passw)
except:
print("Couldn't log")
I get no exception and all is working good.
therefore I know getpass is not returning a normal string and I need to cast my string to a getpass object
Is there any option to do that?
Thanks in advance!
------Edit------
as #Chris mentioned in the comments, getpass returns a normal string. The problem was with the "obj.client.cloud" it had a line break inside of it that's why when I've printed both strings I thought they were the same.
You can check the object type using type(obj) as #Chris pointed.
and you can check if both are the same using ("string" == getpass.getpass()) and it will return if true.
im trying to do a menu. I have a validation to don´t accept string input. If the value ins numeric the function goes well but when the input is a string, something go wrong
def menudos(diccionario, titulo):
os.system('clear')
list_menu = []
if diccionario:
print(titulo)
for key in diccionario:
list_menu.append(key)
list_menu.append("Volver")
for x in range(0, len(list_menu)):
print(x, ": ", list_menu[x])
try:
opcion = int(input("Seleccionar> "))
except:
menudos(diccionario, titulo)
return list_menu[opcion]
The error is that:
Traceback (most recent call last):
File "menudos.py", line 23, in <module>
print(menudos(a, "Prueba"))
File "menudos.py", line 21, in menudos
return list_menu[opcion]
UnboundLocalError: local variable 'opcion' referenced before assignment
Thanks
The problem is that when you provide not an int, the program raises the exception trying to convert non-int to int and nothing is assigned to your var opcion. If you want to protect your program from crashing. Execute try..except statement in an infinite loop waiting for the correct format of the index.
The specific traceback is caused because opcion is not defined in the except block, but you are trying to return list_menu[opcion] after going through the except block.
Instead, I would suggest that you use a while loop that will run forever until you get acceptable input from the user.
My approach to user menus has always been to separate the printing of the menu options and capturing the user input.
Something like:
def print_menu():
print("Please make a selection:")
print("1. Do item #1")
print("2. Do item #2")
# ...etc....
def get_user_input():
selection = None
while selection is None:
try:
selection = int(input("Selection: "))
return selection
except:
print("You selected an invalid choice. Please choose again.")
print_menu()
Hope this helps!
Edit: Also see this question on recursion in Python. There is a limit of 1000 recursive calls by default in Python - so, assuming your existing code worked, a user could enter 1000 incorrect entries and break your program.
I need help with this code as I don't know where I've gone wrong with this as I want the if statement to read abc first then def after so then it can say access granted. Here is the code below:
file=open("test.txt","r")
username = input("enter username")
if file.read() == username:
print("Enter password")
else:
print("enter password")
password = input()
if file.read() == password:
print ("acsess granted")
else:
print ("access denied")
Here is the text file contents:
abc
def
The problem that I'm getting with this is that it will always output access denied where as both abc and def have been in both separate lines. I have used f.readlines() however this also outputs the same message. Putting a \n in the code will result in this error message:
Traceback (most recent call last):
File "/Users/boys/Documents/test.py", line 8, in <module>
if file.read('\n') == password:
TypeError: integer argument expected, got 'str'
Note: I will have to have more than one username and password for this, and a admin username and admin password.
The problem is that readline() includes the newline (\n) at the end. The splitlines() function is one way to work around this:
file=open("test.txt","r")
text = file.read().splitlines()
username = input("enter username")
if text[0] == username:
print("Enter password")
password = input()
if text[1] == password:
print ("acsess granted")
else:
print ("access denied")
else:
print("Wrong username!")
EDIT: I also fixed the logic so that an incorrect password but correct username no longer prints "access granted" (which I assume was not the OP's intended beahvior).
First, your code has a security issue - your user is able to recognize correct username without yet entering a password.
Second, it is a little complicated, so I give you another one
with open("test.txt") as inp:
u_name = inp.readline()
p_word = inp.readline()
username = input("Enter username: ")
password = input("Enter password: ")
if username == u_name.strip() and password == p_word.strip():
print("Access granted")
else:
print("Access denied")
Some explanation:
Use a context manager (with) instead of direct open() - it safely closes your file in all situations and gives you other advantages.
"r" is the default, so you may omit it in open() function.
strip() function strips out whitespace symbols (spaces, tabs, newlines, ...) from both ends of a string.
I would comment on Brendan's post, but I still don't have enough rep to add comments, so I'm throwing this into an answer.
A couple other corrections I would suggest is to use RAW_INPUT() over INPUT(), so that you don't need to include quotes when entering in your information. RAW_INPUT assumes a string, while input assumes a number or variable if the quotes are not included.
Also, your first else statement is misleading you (from a validation standpoint). While testing your code, you should have them saying something a little different, maybe adding a number indicator to see which part of the statement the logic hit.
I have attempted to get this code working in Python 3.5.1 but I am having problems with it not writing the hashed password and username to the file specified. Is there something I'm doing wrong?
import sys
import hashlib
import getpass
def main():
print ('\nUser & Password Storage Program v.01\n')
if input('The file will be modieifed if it exists.\nDo you wish to continue (Y/N): ') not in ('Y','y'):
sys.exit('\nChanges were not recorded\n')
user_name = input(str('Please Enter a User Name: '))
pwdinput = input("Now enter a password:").encode('utf-8')
password = hashlib.sha224(pwdinput).hexdigest()
try:
f = open(passfile.txt,'a+')
f.write(user_name + '\n')
f.write(password + '\n')
f.close()
except:
sys.exit('There was a problem writing to the file!')
print ('\nPassword safely stored in passfile.txt.\n')
main()
You don't have a variable called passfile.txt, and that is making the open call fail. It would be correctly opening the file if you surrounded it in quotes, like 'passfile.txt'
The reason this syntax error isn't obvious is because you have a catch all, and your program will just print 'There was a problem writing to the file!' instead.
Rather than catch all exceptions using except:, use the syntax except IOError:, as that will be thrown whenever there is an actual error in writing to the file.
The error is that your open() function is taking an object as a parameter, but you probably meant to use it as a string.
Also, you generally should use a with block when opening files.
try:
with open("passfile.txt",'a+') as f:
f.write("{}\n{}\n".format(user_name, password))
except Exception as e: # Use other exceptions for more accurate results
sys.exit('There was a problem writing to the file!\nError: {}'.format(str(e)))