Use values from another function python3 - python

I have this code, but i dont know how to use the "age" from the user in the other function any clue what i have wrong?
def accounts():
yourCode = input("Please enter your user code. \nIf you already have an account, type your account user code. \nOtherwise, enter a new one to create an account: ")
with open("users.txt", "r") as rf:
users = rf.readlines()
for each_user in [user.split(",") for user in users]:
if each_user[0] == yourCode:
print(f"Welcome {each_user[1]}")
age = each_user[2]
xxApp()
return None
with open("users.txt", "a") as af:
name = input("Please enter your name: ")
age = input("Enter your age: ")
af.write(f"{yourCode},{name},{age}\n")
print(f"Thank you {name}, your information has been added.")
xxApp()
def xxApp():
age = each_user[2]
print(age)

Pass it as a parameter
def accounts():
yourCode = input("Please enter your user code. \nIf you already have an account, type your account user code. \nOtherwise, enter a new one to create an account: ")
with open("users.txt", "r") as rf:
users = rf.readlines()
for each_user in [user.split(",") for user in users]:
if each_user[0] == yourCode:
print(f"Welcome {each_user[1]}")
xxApp(each_user)
return None
...
def xxApp(user):
age = user[2]
print(age)

You're defining age = each_user[2], but the each_user variable is only available in the scope of accounts().
You can read about python scopes here
I would modify the xxApp() function to take in a variable as a parameter like this
def xxApp(each_user):
age = each_user[2]
print(age)
then you call xxApp() with the each_user passed as a parameter, so it is available inside the scope of xxApp(), like this xxApp(each_user)

Related

comparing user input to text file

from pip._vendor.distlib.compat import raw_input
class Login:
def logging_in(self):
StudentID = raw_input("please enter your student id. ")
f = open("StudentDetails.txt", "r+")
lines = f.readlines()
if StudentID == lines:
print("Verified Welcome")
else:
print("you are not a registered Student Goodbye")
f.close()
login = Login()
login.logging_in()
I'm atempting to compare my user input to my variables inside the text file. Every time I atempt to type in a student id (0001,0002) It keeps Printing the you are not a registered student goodbye. How to resolve this?
You can load the valid IDs once when the instance is created. Then when a user tries to login, you just check if the ID exists in that set. For example:
from pip._vendor.distlib.compat import raw_input
class Login:
def __init__(self):
with open("StudentDetails.txt", 'r') as file:
lines = file.readlines()
self.valid_ids = set([s.strip() for s in lines])
def logging_in(self):
StudentID = raw_input("please enter your student id. ")
if StudentID.strip() in self.valid_ids:
print("Verified Welcome")
else:
print("you are not a registered Student Goodbye")
login = Login()
login.logging_in()
You're comparing input ID against a list, you need add a for loop
def logging_in(self):
StudentID = raw_input("please enter your student id. ")
f = open("StudentDetails.txt", "r+")
lines = f.readlines()
for line in lines
if StudentID in line:
print("Verified Welcome")
else:
print("you are not a registered Student Goodbye")
f.close()
BTW, as #Cohan says in comments, any character in line will give access to user. I am assuming this is just for learning purposes, and not a real security approach.

Global variable Issues with different functions (using Python)

I am trying to create a program that allows me to use my list 'users' in a different function in the program.
I have tried parameters, declaring it 'global' (although I've been told it's bad practice to do that) and I've tried researching 'class' and implementing it all to no avail. I have also tried putting users into a text file and then reading from it but it's a nuisance as I need it to be in a list.
Here is my code:
def register():
global username
username = raw_input("Enter a username: ").lower()
firstName = raw_input("Enter your first name: ").lower()
surname = raw_input("Enter your surname: ").lower()
age = raw_input("Enter your age: ")
yearGroup = raw_input("Enter your year group: ")
users =[[firstName, surname, age, yearGroup]]
def resultsFunction():
score = 5
results = [[score, username]]
results.extend(users)
I have tried:
def register():
global username
username = raw_input("Enter a username: ").lower()
firstName = raw_input("Enter your first name: ").lower()
surname = raw_input("Enter your surname: ").lower()
age = raw_input("Enter your age: ")
yearGroup = raw_input("Enter your year group: ")
global users
users =[[firstName, surname, age, yearGroup]]
It throws up the error:
results.extend(userDetails)
NameError: global name 'userDetails' is not defined
The strange thing is, after declaring username 'global' (yes, I know I shouldn't, but it worked), I was able to use the username in the function but when I tried it with the other variables, e.g firstName so I could try to create the list simply in the 'resultsFunction' it wouldn't work.
The register function does not get run all the time if the user decides not to register but I can't change that as I do not want the user to have to always put in their details.
I am so confused and have tried everything I know. I came here as a last resort so I hope that someone can help and that maybe this question can help others having the same difficulties with the local and global variables scopes.
Write global users inside the function to change values in the users variable. Otherwise you can only read it but not change the value inside it.
lis = []
def a():
lis = [1,2]
a()
print(lis)
will print []
where as :
lis = []
def a():
global lis
lis = [1,2]
a()
print(lis)
will print [1,2]
With reference to your program as per my understanding.. this might help..
username = ''
user = []
def register():
global username
global users
username = input("Enter a username: ").lower()
firstName = input("Enter your first name: ").lower()
surname = input("Enter your surname: ").lower()
age = input("Enter your age: ")
yearGroup = input("Enter your year group: ")
users =[[firstName, surname, age, yearGroup]]
def resultsFunction():
score = 5
results = [[score, username]]
results.extend(users)
print(results)
register()
resultsFunction()
will output :-
Enter a username: Foo
Enter your first name: Bar
Enter your surname: Baz
Enter your age: 00
Enter your year group: 00
[[5, 'foo'], ['bar', 'baz', '00', '00']]

Existing file not appending new record

I am trying to create a file as the header and then open it later to append new records, but it seems I am not doing something correctly, does anyone have an idea?
here is the code below:
I have tried it in several ways to no avail.
file = 'Quizdata5.txt'
users = {}
def header():
headers = ("USERID LOGIN-NAME SURNAME NAME AGE "
" YEAR-GROUP SEX USERNAME\n")
with open(file, 'w') as file1:
file1 .write(headers)
file1.close()
def newUser():
global users
global header
global createLogin
global createPassw
global surname
global name
global age
global y_group
global sex
global z1
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print("\nLogin name already exist, please choose a different name!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
#return (users[createLogin])
surname = input("Pls enter your surname: ")
name = input("Pls enter ur name: ")
age = input("Pls enter your age: ")
y_group = int(input("Please enter your year group: "))
sex =input("Please enter your sex: ")
print("\nUser created!\n")
print("*********************************")
print(" Your Name is\t" + name, "and it starts with: " + name[0] + "\n")
z1 = createPassw[:3] + age
print(" Your Username is:\t ", z1)
if __name__ =='__main__':
header()
while newUser():
with open(file, 'a') as file2:
rows = ("{:8} {:8} {:8} {:8} {:8} {:8}"
" {:8} {:8} \n".format(createLogin, createPassw,
surname, name, age,
y_group, sex, z1))
file2.write(rows.split())
file2.close()
#enter code here
Working version below. Note that I changed your input statements to raw_input. I'm using Python 2.7. Main things needed:
a choice to exit outside AND inside the while loop
build a list for existing users for the existing username check
fixing your formatting for row
Not splitting your row when you write it
Seems to be working now and ready for more improvements. Build a little and test until working, then build more - saves a ton of time!
file = 'Quizdata5.txt'
users = {}
def header():
headers = "USERID LOGIN-NAME SURNAME NAME AGE YEAR-GROUP SEX USERNAME\n"
with open(file, 'r') as file1:
firstLine = file1.readline()
print firstLine
if firstLine == headers:
print 'Headers present'
return
with open(file, 'w') as file1:
file1.write(headers)
def newUser():
userList = []
with open(file, 'r') as file1:
Lines = file1.readlines()
for line in Lines[1:]:
lineArray = line.split(' ')
userList.append(lineArray[0])
print userList
global users
global header
global createLogin
global createPassw
global surname
global name
global age
global y_group
global sex
global z1
createLogin = raw_input("Create login name or enter 'exit' to quit: ")
if createLogin == 'exit':
return False
while createLogin in userList: # check if login name exists
print("\nLogin name already exist, please choose a different name!\n")
createLogin = raw_input("Create login name or enter 'exit' to quit: ")
createLogin = createLogin.strip()
if createLogin == 'exit':
print('Goodbye for now.')
return False
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
# return (users[createLogin])
surname = raw_input("Pls enter your surname: ")
name = raw_input("Pls enter ur name: ")
age = raw_input("Pls enter your age: ")
y_group = int(raw_input("Please enter your year group: "))
sex = raw_input("Please enter your sex: ")
print("\nUser created!\n")
print("*********************************")
print(" Your Name is\t" + name, "and it starts with: " + name[0] + "\n")
z1 = createPassw[:3] + age
print(" Your Username is:\t ", z1)
return True
if __name__ =='__main__':
header()
while newUser() == True:
with open(file, 'a') as file2:
row ="{a} {b} {c} {d} {e} {f} {g} {h}\n".format(
a=createLogin, b=createPassw, c=surname, d=name, e=age, f=y_group, g=sex, h=z1)
file2.write(row)
Without just rewriting your code outright, your problem is the line
while newUser():
This means call newUser(), and execute the indented code only if the return value of newUser(), evaluated as a boolean, returns True. That is bool(newUser()) is True.
Now the questions are
a) What does newUser() return and,
b) What does bool() mean?
First b: All objects in Python have some "boolean" value associated with it, True or False. For a lot of built-in types their boolean evaluation makes sense. For example the integer 0 is treated as False in a boolean context, while any non-zero integer is treated as True. This is the case in most any programming language with some exceptions.
Similarly an empty list [] is False in a boolean context (which is why we can write things like if not my_list: ... to test if a list is empty) while any non-empty list is treated as True and so on.
As for a:
Your newUser() function doesn't explicitly return and any result, because you don't have a return statement (Tom's solution added some). What you want to do is return a True-ish value when a new user is added, and a False-ish value when no new users are to be added. But since you don't return anything, in fact, the default return value for functions if Python, if you don't explicitly return, is a value called None and it is always False.
So the end result is that the code under your while statement is never run.
If you're ever in doubt about what your code is doing walk through it line by line and see exactly what it's doing--what functions are returning and what values are being assigned to variables--by using the pdb debugger (Google will direct you quickly to some good tutorials). With Python in particular there's no reason to ever be in the dark about what your code is actually doing.

my login method is not being called within my register() and my error in mainError(0 comes up when it's not supposed to

This is my code:
import time
print("Welcome to the quiz")
print("Would you like to login with an existing account or register for a new account?")
def login():
userQ = input("Please enter your username: ")
passQ = input("Please enter your password: ")
#In progress of making...
def register():
print ("Your username will now be created from your first name and age.")
fname = input("Please enter your first name: ")
age = input("Please enter your age: ")
fname2 = fname[:3]
username = fname2 + age
print ("Your username is {}".format(username.upper()))
password = input("Please enter a password for your new account: ")
time.sleep(1.0)
print ("Username: {}".format(username))
print ("Password: {}".format(password))
with open("UserPass.csv", "w") as f:
for line in f:
file = line.split(",")
f.write(username) in file[0]
print ("ACCOUNT CREATED")
login()
class validation(Exception):
def __init__(self, error):
self.error = error
def printError(self):
print ("Error: {} ".format(self.error))
def mainError():
try:
raise validation('Please enter a valid input')
except validation as e:
e.printError()
def Menu():
while True:
options = ["Login", "Register"]
print("Please, choose one of the following options")
num_of_options = len(options)
for i in range(num_of_options):
print("press " + str(i + 1) + " to " + options[i])
try:
uchoice = int(input("? "))
if uchoice == 1:
print("You chose to " + options[uchoice - 1])
login()
break
elif uchoice == 2:
print("You chose to " + options[uchoice - 1])
register()
break
elif (uchoice - 1) > len(options):
mainError()
except ValueError:
mainError()
Menu()
In my code, if the user chooses to register for a new account, it runs the 'register()' method. After the user are their username and password in the method, it writes it to a csv file and then calls the login() method. BUT, instead... it somehow runs the Menu() method instead and ignores my login().
In addition, after the end of the register method is reached, it prints an error message that I made with my 'Class Validation(Exception) and 'mainError()' which I don't want it to - I don't understand why it does this as I have not called mainError().
An example of when I run the code and choose to register:
Welcome to the quiz
Would you like to login with an existing account or register for a new account?
Please, choose one of the following options
press 1 to Login
press 2 to Register
? 2
You chose to Register
Your username will now be created from your first name and age.
Please enter your first name: Siddharth
Please enter your age: 16
Your username is SID16
Please enter a password for your new account: shamrock
Username: Sid16
Password: shamrock
Error: Please enter a valid input
Please, choose one of the following options
press 1 to Login
press 2 to Register
?
As you can see, it goes to the Manu() instead of login() after the registration and before it, prints "Error: Please enter a valid input" when there is no need.
How can I fix this. Thank you!
Change
with open("UserPass.csv", "w") as f:
for line in f:
file = line.split(",")
f.write(username) in file[0]
to
with open('UserPass.csv', 'a') as f:
f.write('whatever text you want to save')

When I run the program it asks for my input multiple times even after I've entered it once already

When I run the program it asks for my input multiple times even after I've entered it once already.
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
Asks the user to input a name which is the key to a value, which it returns
for i in Peeps:
if i == input("Type in a name: "):
print("The amount", [i], "owes is:", "$" + str(Peeps[i]))
break
else:
print("Sorry that name does not exist, please enter a new name.")
You need to ask the user input first instead of comparing the user input directly to the key.
You do not want to do it like that. Take a look at the following instead:
Peeps = {"Juan":244, "Jayne":433, "Susan":751}
name = input("Type in a name: ")
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
You do not have to loop through your dict and check the user input against each value individually (plus you are forcing the user to update\re-enter his input continuously).
Just receive it once and process it.
If you want to keep the loop running to allow for multiple queries, use while like so:
Peeps = {"Juan": 244, "Jayne": 433, "Susan": 751}
name = input("Type in a name or leave blank to exit: ")
while name:
if name in Peeps:
print("The amount", name, "owes is:", "$" + str(Peeps[name]))
else:
print("Sorry that name does not exist, please enter a new name.")
name = input("Type in a name or leave blank to exit: ")

Categories