Reputation: 3
I am making a registration module for a Python Quiz which I am developing, solely to improve my programming technique. Here is my code:
def quiz():
print('success')
def loginPage():
fr=open("ddddfile.txt",'r').read()
v=False
while v==False:
un=input('Please enter your username.')
pw=input('Please enter your password.')
v2=0
print(fr[v2][2], fr[v2][3])
if fr[v2][3]==un and fr[v2][4]==pw:
print('Successfully logged in.')
v=True
quiz()
else:
print('Incorrect username or password. Please try again.')
v2+=1
def registerPage():
v=0
while v<3:
n=input('Please enter your name.')
if n==str(n):
v+=1
a=input('Please enter your age.')
if int(a)>10 and int(a)<20:
v+=1
yg=input('Please enter your year group.')
if int(yg)>6 and int(yg)<15:
v+=1
un=n[:3]+a
print('Your new username is', un, '. Please remember this as you will need it to log in.')
v=False
while v==False:
pw=input('Please enter your desired password.')
pwc=input('Please re-enter your password.')
if pw==pwc:
v=True
usrInf=[n,a,yg,un,pw]
fw=open("ddddfile.txt",'r+')
fw.write(',')
fw.writelines(str(usrInf))
fw.close()
loginPage()
def startPage():
c1=input('Welcome to the Quiz. Please type "login" or "register".')
v=False
while v==False:
if c1.lower()=='login' or c1.lower()=='l':
v=True
loginPage()
elif c1.lower()=='register' or c1.lower()=='r':
v=True
registerPage()
else:
c1=input('Please type "login" or "register".')
startPage()
As you can see, I am storing user data in an external text file. The contents of the text file is as follows:
[['Xavier Pamment', '16', '11', 'Xav16', 'nL4WVba2KR'],[]]
However, in the loginPage() function, when run, once the code tries to validate the user inputted details, I get this error:
Traceback (most recent call last):
File "C:\Users\xavier\Desktop\dddd.py", line 58, in <module>
startPage()
File "C:\Users\xavier\Desktop\dddd.py", line 52, in startPage
loginPage()
File "C:\Users\xavier\Desktop\dddd.py", line 10, in loginPage
print(fr[v2][2], fr[v2][3])
IndexError: string index out of range
Does anyone know where I have slipped up? Thanks, CH
Upvotes: 0
Views: 166
Reputation: 532
When you do fr=open("ddddfile.txt",'r').read()
, you are getting the contents of the file in the form of a string. You need to convert that string into a list before trying to index it in the way that you are. You should look into ast.literal_eval
.
Upvotes: 1