Issue with referencing a global variable within a function - python

This is further to an issue I asked about on here yesterday What is the best way to validate user input against the contents of a list?). I got a good suggestion using a function like so:
getuser = input("Please enter your username :")
print("1. render_device")
print("2. audit_device")
askuser = input("Would you like to render_device or audit_device? : ")
def verify_input(sites_set):
get_site_name = input("Please enter the site name you'd like to render :")
if get_site_name in sites_set:
print('Proceed')
return
else:
print('Not in either list, please enter a valid site')
verify_input(sites_set)
if askuser == "1":
sites_2017 = ["bob", "joe", "charlie"]
sites_2018 = ["sarah", "kelly", "christine"]
verify_input(set(sites_2017 + sites_2018))
This works correctly within the function and when it is called. However, the issue is that I need get_site_name as a global variable since its input is referenced later in the script (not in a function). When I make get_site_name global, the function can reference it and works correctly when a valid site is input, but when an invalid site is input it just keeps looping the "Not in either list" error over and over, probably because the raw_input in the get_site_name variable isn't defined locally.
What would be the best way to remedy this?

What about:
def verify_input(sites_set):
while get_site_name not in sites_set:
get_site_name = input("Please enter the site name you'd like to render :")
print('Proceed')
return

Related

How can I access a variable before I declare it?

I am a total amateur when it comes to python and I have came across an issue:
if input() == existingUsername:
print('Sorry, that username is taken, please try again:')
However, I need to access exisingUsername before it is declared, because I've defined it at the bottom of my code. I know you can do this in javascript with the let variable, but how can I do it in python?:
let existingUsername;
//code
existingUsername = 'name'
You can't use a variable before declaring it.
You could however use an empty string:
existingUsername = ""
# .
# .
# the rest of your program
# .
# .
username = input()
if username == existingUsername:
print('Sorry, that username is taken, please try again:')
else:
# assign new username here
existingUsername = username

Python If Statement question login system easy

The first thing to do is write "1" and then enter username and password. After that, the max number of account is 1 and you can then use the "2" to login.
First time asking a question so I am sorry if this is like a dumb question or something. My code is as following:
https://imgur.com/a/dAaYf2u - NEW LINK
Code:
print("Type 1 for Create user. Type 2 for login")
Choice = input("Number here: ")
if Choice == ("1"):
print("Welcome to the Create a user interface")
Username = input("Username: ")
Password = input("Password: ")
if Password.count("!") > 0:
print("Not valid - no special characters!")
else:
file = open("account.txt", "w")
file.write(Username)
file.write("\n")
file.write(Password)
file.close()
elif Choice == ("2"):
print("Welcome, please type your Username and Password")
Loginu = input("Write username here: ")
Loginp = input("Write password here: ")
file = open("account.txt", "r")
first_line = file.readline()
if Loginu == first_line:
print("you're logged in")
else:
print("fail")
It's very basic and so on. What I don't understand is why the if Loginu == first_line can't read the first_line variable... It just jumps directly to else:
I hope it helps and I know my code is very basic lol.
My advice:
follow pep8, use meaningful names for variables
split your code into functions
use infinite loop for your "menu"
even better use some package that helps with building such applications (click?) rather then reinvent the wheel
Read your file with with open(...) as f: context manager
It's probably good idea to read whole file and build dictionary instead of depending on the login to be exactly identical with first line
use strip() to remove white characters (like newline)
check that line you are looking at is not empty
if you've opened file without context manager for writting, you need to close it before opening it again for reading
use debugger to check what's exactly result of readline

Entering input code but doesn't ask me for input when I run

I have this code below:
def my_function(username,greetings):
username = input("enter your name:")
print("Hello %s , I wish you %s"%(username,greetings))
I would expect to be asked for the input when I run it, but it doesn't show the "enter your name:"
great work so far, what you're doing wrong, is the username have to be instantiated before passing it as parameter to the function,
# declating the function
def my_function(username,greetings):
print("Hello %s , I wish you %s"%(username,greetings))
#reading the username from the user input
username = input("enter your name:")
# initiating greetings variable
greetings = 'some greetings'
#calling the function with the previously declared variables
my_function(username, greetings)
I believe this is what you're looking for.
def my_function(username, greetings):
print("Hello %s , I wish you %s"%(username, greetings))
username_input = input("enter your name:")
greetings_input = input("enter your greeting:")
my_function(username_input, greetings_input)
Explanation
def my_function() has the function definition which takes two parameters i.e username and greetings as inputs to the function. The function prints the statement Hello ..., I wish you ... with appropriate replacements
When you run the python code, the line username_input requests the user for an input of the name and the result is stored in the variable. Similarly with greeting_input.
You then have to call the function by using the name of the function i.e. my_function() with the appropriate parameters taken as input. So the function call happens by doing my_function(username_input, greeting_input)
All the best with your learning. Hope this helps

Python prints None despite not being inside function

So I'm still relatively new to Python programming and so at the moment I'm just trying to create a simple password program. If the use has opened the program before, then it will skip the create a password bit. I have done this by creating a file which will contain the number of times the file has been opened. If the number is less than 1 then it will ask for the new password.
This bit works fine, I just have the problem that when running the following code, "None" is printed. I understand the whole function return bit but the code I'm using isn't in a function so I'm not sure why it is happening. Would really appreciate help in fixing this!
fo = open("openNo.txt", "r")
openNo = fo.read()
if int(openNo)<1:
pw = input(print("Please enter a password: ")) #creating a new password
pwCheck = pw
else:
pwCheck = input(print("Please enter your password: ")) #using an existing password
fo.close()
if pwCheck == "password":
print("Welcome!")
else:
print("access denied")
You are doing that, in fact: you are passing the result of print to input. There's no need to do that.
pw = input("Please enter a password: ")
print("Please enter a password: ") returns none so you are seeing none when you run the code

How to create a python dictionary that will store the username and password for multiple accounts

The problem I have right now is that for my dictionary that uses a key:value to store username:password is that every time I rerun the program, the current key:value is reset and the dictionary is set to empty again. The goal of my program is to have a person log in with a username and password and be able to store notes and passwords (I did this with python .txt files). Then the next person can come along, create an account and do the same. Here is my code (I have commented every line of code pertaining to my problem):
def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = input("Please Set Your New Username: ")
password = input("Please Set Your New Password: ")
// if (userName in dictAcc):
print("Username is taken")
userPass()
else:
// dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
time.sleep(1.5)
dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
// for key in dictAcc:
// if (loginUserName == key and loginPass == dictAcc[key]):
// print("You have successfully logged in!")
dataInput()
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(300)
login()
userPass()
As others have mentioned, you need to have your dictionary saved into a file and load it when you restart your program. I adjusted your code to work for me and created two functions, one to save the dictionary (savedict) and another to load it (loaddict). The except IOError part is just so that it creates a new file if it doesn't exist.
Note that in general, storing passwords in a text file is a very bad idea. You can clearly see the reason why if you try to open the "dictAcc.txt" file (it will have all passwords there).
import pickle
import time
def loaddict():
try:
with open("dictAcc.txt", "rb") as pkf:
return pickle.load(pkf)
except IOError:
with open("dictAcc.txt", "w+") as pkf:
pickle.dump(dict(), pkf)
return dict()
def savedict(dictAcc):
with open("dictAcc.txt", "wb") as pkf:
pickle.dump(dictAcc, pkf)
def userPass():
dictAcc = loaddict() #Load the dict
checkAccount = raw_input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = raw_input("Please Set Your New Username: ")
password = raw_input("Please Set Your New Password: ")
if (userName in dictAcc):
print("Username is taken")
userPass()
else:
dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
savedict(dictAcc) #Save the dict
time.sleep(1.5)
# dataInput() Code ends
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = raw_input("Type in your Username: ")
loginPass = raw_input("Type in your Password: ")
dictAcc = loaddict() #Load the dict
if (tries < 3):
for key in dictAcc:
if (loginUserName == key and loginPass == dictAcc[key]):
print("You have successfully logged in!")
# dataInput() Code ends
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(3)
tries=1 #To restart the tries counter
login()
global tries
tries=1
userPass()
There are different ways to do this. I'll mention two.
As you noticed, all variables created by your program are erased when the program finishes executing.
One way to keep those variables alive is to keep the program running indefinately; something like a background process. This could be achieved very simply by running the script within a while loop while True:, although there are more effective ways to do it too. Then, it's variables can continue to exist because the program never terminates.
However that is only useful in occasions when you want to have something running all the time, such as a user interface waiting for input. Most of the time, you want your script to run and be able to complete.
You can therefore output your needed data to a text file. Then, when you start your program, read that text file and organize the info into your dictionary. This will make use of open("Your_username_file") and reading that file's data. If you need help on how to do that, there are many tutorials about how to read information from files in Python.
How you will store it doesn't matter too much in your case, so it's better to keep things simple and store it in something like a text file. In anycase, you don't want to store the accounts in memory, because you will need to keep it running forever.
Since this is also running locally, no matter how you choose to store your passwords, it'll be accessible to anyone who uses it. So User_a can check User_b's account and password.
So you'll need to encrypt the password before storing them. It's not as hard as it sound. Actually, Python has built-in libraries to deal with it.
A quick google search returned a simple tutorial explaning all this step by step, check it out. You'll probably be able to implement it into your code very quickly.

Categories