Python Intended Block error - python

I am sorry but i have a problem that i dont understand...
def login_screen():
print(30 * "-")
print(" LOGIN")
print(30 * "-")
username = print("Please enter your username: ")
password = print("Please enter your password: ")
with open('logins.txt', 'r') as csvfile:
loginreader = csv.reader(csvfile, delimiter=',', quotechar= None)
for codes in loginreader:
if len(codes) == L_LEN:
if codes[L_USERNAME] == username and codes[L_PASSWORD] == password and codes[L_ADMIN] == "Yes":
admin_console()
elif username == row[L_USERNAME] and password == row[PASSWORD] and row[L_ADMIN] == "No":
#Temp normal console here
else:
clearscreen()
error_head()
print("Unknown account")
input("Press [ENTER] To continue...")
login_screen()
elif len(codes) != M_LEN:
next(csvfile, None)
So the problem is that it comes with the following error:
File "G:\Python\DatabaseStandardRewrite\Login.py", line 49
else:
^
IndentationError: expected an indented block
But i dont get it! (Yes, all the other things are defined in the rest of the document!
Does anyone of you see my mistake?
Natan

Python does not permit blocks to be empty; you need at least one statement, and a comment does not count. So in the elif block before your else, you should put pass.
elif username == row[L_USERNAME] and password == row[PASSWORD] and row[L_ADMIN] == "No":
#Temp normal console here
pass
else:
clearscreen()

Related

Having trouble preventing users from registering with a duplicate username on Python

I'm a student who is doing my Python assignment. Thing is, our lecturer is really strict on us not using python built ins and also refuses to check our code before submission and I'm having the hardest time trying to get my code to work properly during registration.
My problem currently is that I want the code to prompt an error from the program itself when the user tries to register with a taken username. However, it keeps running different errors regardless of how I try to fix it. Can anyone please point me in the right direction or tell me what's wrong with my code? I'd be really grateful for any help.
def grant():
print("Helllooooo")
def begin():
while True:
print("Welcome to the Freshco Groceries App!")
option = input("Are you a new or returning user?\n"
"Enter 1 if you would like to LOGIN\n"
"Enter 2 if you would like to register\n"
"Enter 3 if you would like to exit the program\n")
if option=="1":
access(option)
break
elif option=="2":
access(option)
break
elif option=="3":
print("Thank you! Have a good day.")
exit()
else:
continue
def access(option):
if(option=="1"):
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
login(name,password)
else:
print("First step: Please choose a username and a unique password.")
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
register(name,password)
newuser()
def login(name,password):
success=False
file = open("user_details.txt","r")
for line in file:
a,b = line.split(",")
if (name in a) and (password in b):
success=True
break
file.close()
if(success):
print("You have successfully logged in! Happy shopping!")
grant()
else:
print("Wrong username or password entered.")
def register(name,password):
exist = False
while True:
file = open("user_details.txt", "r")
for line in file:
line = line.rstrip()
if (name == line):
exist = True
break
else:
pass
file.close()
if (exist):
print("Username has been taken. Please try again with a new one.")
break
else:
file = open("user_details.txt","a")
file.write("\n" + name + "," + password)
print("You have successfully registered! Welcome to the Freshco Family!")
grant()
break
def newuser():
print("Before you start using the app, please fill in the details below.")
alldata = []
while True:
newdata = []
nname = input("Please enter your full name:\n")
newdata.append(nname)
while True:
ngender = input("Are you female or male?\n"
"1: female\n"
"2: male\n")
if ngender=="1":
fingender="female"
newdata.append(fingender)
break
elif ngender=="2":
fingender="male"
newdata.append(fingender)
break
else:
print("INVALID INPUT")
continue
naddress = input("Please enter your address:\n")
newdata.append(naddress)
nemail = input("Please enter your email address:\n")
newdata.append(nemail)
ncontact = input("Please enter your contact number:\n")
newdata.append(ncontact)
ndob = input("Please enter your dob in this format: <DD.MM.YY>\n")
newdata.append(ndob)
alldata.append(newdata)
print(newdata)
break
print("Thank you for entering your information, you will be redirected now!")
grant()
begin()
thank you so much! T-T

displayMenu() - function is not defined error

The menu provides input options to the user. The main focus is on having the functions being called without error as previously experienced. The resolution was that my code was incorrectly formatted. displayed() first then login() and register().
Resolution:
def displayMenu():
global menu_input
menu_input = input("Please enter one of the following options:\n r - register user\n a - add task\n va- view all tasks\n vm - view my tasks\n e - exit\n")
if menu_input == "r":
register()
elif menu_input == "a":
add_task()
elif menu_input == "va":
view_all()
elif menu_input == "vm":
view_more()
elif menu_input == "e":
exit()
return menu_input
displayMenu()
def login():
username = input("Please enter your username?:\n")
password = input("Please enter your password?:\n")
for line in open("user.txt","r").readlines():
field = line.strip().split(",")
if username == field[0] and password == field[1]:
print("Username & Password Correct!\n")
return True
print("Username & Password Incorrect\n")
return False
login()
def register():
register = False
while register == False:
username = input("Please enter a username?: ")
password = input("Please enter a password?: ")
password_check = input("Please re-enter the password?:")
if password == password_check:
file = open("user.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
register = True
print ("Your login details have been saved. ")
else:
print("Passwords doesn't match!")
register()
You should declare the register function before you call to the displayMenu().
Try to move you function declarations to the top of your code.
The resolution for me was moving my function login() below all my other functions without calling them unless in the displayMenu() & displayMenu_Admin().
Also, I had to read up on functions() as I didn't understand the concept fully.

How to fix unknown login after multiple atemps

When I log in as an "existing user", it works perfectly when I log in first try
But in the while loop, when I get the login incorrect and it prompts me again and THEN I get the login correct, it comes up as login failed
import sys
existing = " "
possibleAnswersExisting = ["y","n"]
accountFileW = open("AccountFile.txt","a")
accountFileR = open("AccountFile.txt","r")
while existing not in possibleAnswersExisting:
existing = input("Are you an already existing user? (Please input y/n)\n>>")
if existing not in possibleAnswersExisting:
print('Please enter a valid answer. (Only "y" or "n")')
def register():
username = input("What would you like your username to be?")
password = input("What would you like your password to be?")
print("Welcome" ,username + "! Make sure to remember your password or write it down in case your forget!")
accountFileW.writelines([username, " ", password, "\n"])
def login():
x = ""
attempts = 0
while x != True:
lusername = input("What is your username? (CaSe SeNsItIvE PleAsE)\n>>")
lpassword = input("What is your password? (CaSe SeNsItIvE PleAsE)\n>>")
for line in accountFileR:
print("in for loop")
loginInfo = line.split()
print(loginInfo)
if lusername == loginInfo[0] and lpassword == loginInfo[1]:
print("--Successful login, setting x to true")
x = True
break
attempts = attempts + 1
if str((4 - attempts)) == 0:
print("Error, login credentials invalid. Exiting program...")
sys.exit()
if attempts > 0 and attempts < 5:
print("Incorrect" ,str((4 - attempts)), "attemptsleft.")
print("Successful login")
if existing == "n":
register()
elif existing == "y":
login()
else:
print("Error with existing")
sys.exit()
accountFileW.close()
accountFileR.close()
I expect the output for the login to be successful, but it says incorrect unlike when I get it right the first try
After Python has read a file, its "Prompt" is at the end of the file. If you do call read on the fileobject again it will return nothin since there is nothing left to read.
With seek(x) you can place the "Prompt" to the postion x. In you case 0 since you want to read the file again.
I injected the line on the right place:
import sys
existing = " "
possibleAnswersExisting = ["y","n"]
accountFileW = open("AccountFile.txt","a")
accountFileR = open("AccountFile.txt","r")
while existing not in possibleAnswersExisting:
existing = input("Are you an already existing user? (Please input y/n)\n>>")
if existing not in possibleAnswersExisting:
print('Please enter a valid answer. (Only "y" or "n")')
def register():
username = input("What would you like your username to be?")
password = input("What would you like your password to be?")
print("Welcome" ,username + "! Make sure to remember your password or write it down in case your forget!")
accountFileW.writelines([username, " ", password, "\n"])
def login():
x = ""
attempts = 0
while x != True:
lusername = input("What is your username? (CaSe SeNsItIvE PleAsE)\n>>")
lpassword = input("What is your password? (CaSe SeNsItIvE PleAsE)\n>>")
accountFileR.seek(0) # <---- injected line
for line in accountFileR:
print("in for loop")
loginInfo = line.split()
print(loginInfo)
if lusername == loginInfo[0] and lpassword == loginInfo[1]:
print("--Successful login, setting x to true")
x = True
break
attempts = attempts + 1
if str((4 - attempts)) == 0:
print("Error, login credentials invalid. Exiting program...")
sys.exit()
if attempts > 0 and attempts < 5:
print("Incorrect" ,str((4 - attempts)), "attemptsleft.")
print("Successful login")
if existing == "n":
register()
elif existing == "y":
login()
else:
print("Error with existing")
sys.exit()
accountFileW.close()
accountFileR.close()

"No Such File or Directory" in Python

I'm trying to create an encryption program that is also capable of using a username and password to be accessed, alongside the password being able to be changed, however, I am getting the following error when trying to read the password from a file.
Traceback (most recent call last):
File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 28, in <module>
password()
File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 9, in password
var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Matthew\\AppData\\Local\\Programs\\Python\\Python37-32\\password.txt'
Password is saved in the Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt directory.
Below is the code.
import os
import time
def password():
while True:
username = input ("Enter Username: ")
password = input ("Enter Password: ")
var1 = "admin"
var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
if username == var1 and password == var2:
time.sleep(1)
print ("Login successful!")
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
var2 = input("Enter new password: ")
elif input == "N" or "n":
break
logged()
break
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to the encryption program.")
password()
def main():
result = 'Your message is: '
message = ''
choice = 'none'
while choice != '-1':
choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
if choice == '1':
message = input("\nEnter the message to encrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print (result + '\n\n')
result = ''
elif choice == '2':
message = input("\nEnter the message to decrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print (result + '\n\n')
result = ''
elif choice != '-1':
print ("You have entered an invalid choice. Please try again.\n\n")
elif choice == '-1':
exit()
main()
Any help is appreciated, thanks!
Provide the complete path:
var2 = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/password.txt","r")
Edit:
As you said in the comment that it worked but the password was marked as incorrect, so I have fixed issues with your code.
You cannot read data directly by opening a file. You will have to use the command read to get the data:
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()
Your second code problem is setting new password. The code you made:
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
var2 = input("Enter new password: ")
elif input == "N" or "n":
break
Don't use input to see the value, use the variable in which you stored the input data. Also lower the string to make it easy:
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
var2 = input("Enter new password: ")
elif answer.lower() == "n":
break
The full code can be like:
import os
import time
def password():
while True:
username = input ("Enter Username: ")
password = input ("Enter Password: ")
var1 = "admin"
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()
if username == var1 and password == var2:
time.sleep(1)
print ("Login successful!")
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
var2 = input("Enter new password: ")
elif answer.lower() == "n":
break
logged()
break
else:
print ("Incorrect Information!")
def logged():
time.sleep(1)
print ("Welcome to the Encryption program.")
password()
def main():
result = 'Your message is: '
message = ''
choice = 'none'
while choice != '-1':
choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
if choice == '1':
message = input("\nEnter the message to encrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print (result + '\n\n')
result = ''
elif choice == '2':
message = input("\nEnter the message to decrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print (result + '\n\n')
result = ''
elif choice != '-1':
print ("You have entered an invalid choice. Please try again.\n\n")
elif choice == '-1':
exit()
main()

Python Coursework tidying

I need help with a one or two things on my coursework. firstly when I input an incorrect username/password it will output more than one error message at a time. Secondly, when the men function ends the program will go back to the login loop( that allows the user to re-enter their username/password), I have fixed this by using the B variable but this feels extremely janky and I know there is a better way of doing it. Any Modifications or Tips are greatly appreciated (even if they're not related to my above problems). also the way i code is a bit weird so it's probs best you read from bottom to top :)
def quiz():
print ("quiz")# place holder for real code (let's me know the function has been run)
def report():
print ("report") # place holder for real code (let's me know the function has been run)
def a_menu():# Admin menu
print ("Welcome to the student quiz!")
print ("Please choose a option")
while True:
print ("1: Computer science")
print ("2: Histroy")
print ("3: Reports")
menu_in = int(input())
if menu_in == 1:
Comp_sci = True
quiz()
break
elif menu_in == 2:
Hist = True
quiz()
break
elif menu_in == 3:
report()
break
else:
print ("Invalid input! Please try again..")
def menu():
print ("Welcome to the student quiz!")
print ("Please choose a quiz")
while True:
print ("1: Computer science")
print ("2: Histroy")
menu_in = int(input())
if menu_in == 1:
Comp_sci = True
quiz()
break
elif menu_in == 2:
Hist = True
quiz()
break
def login():
b = False
print ("Please enter your username and password")
while True:
if b == True:
break
log_user = input("Username:")
log_pass = input ("Password:")
with open("D:\\Computer science\\Computing test\\logindata.txt","r") as log_read:
num_lines = sum(1 for line in open('D:\\Computer science\\Computing test\\logindata.txt'))
num_lines = num_lines-1
for line in log_read:
log_line = log_read.readline()
log_splt = log_line.split(",")
if log_user == log_splt[0] and log_pass == log_splt[2]:
if log_splt[5] == "a": # Admin will have to mannually change the admin status of other user's through .txt file.
b = True
a_menu()
else:
b = True
log_read.close()
menu()
break
else:
print ("Incorrect username or password, please try again!")
def register():
print ("enter your name, age, and year group and password")
while True:
reg_name = input("Name:")
reg_pass = input ("Password:")
reg_age = input ("age:")
reg_group = input ("Year Group:")
print ("Is this infomation correct?")
print ("Name:",reg_name)
print ("password:",reg_pass)
print ("Age:",reg_age)
print ("Year Group:", reg_group)
reg_correct = input ("[Y/N]").lower()
if reg_correct == "y":
reg_user = reg_name[0:3]+reg_age
reg_write = open("D:\\Computer science\\Computing test\\logindata.txt","a")
reg_write.write (reg_user+","+reg_name+","+reg_pass+","+reg_age+","+reg_group+","+"u"+"\n")
print ("Your username is:",reg_user)
reg_write.close()
login()
break
elif reg_correct == "n":
print ("Please Re-enter your infomation")
else:
Print ("Invalid input! Please try again...!")
def login_ask():
print ("Do you already have an account?")
while True:
ask_in = input("[Y/N]").lower()
if ask_in == "y":
login()
break
elif ask_in == "n":
register()
break
login_ask()

Categories