-3
tries= 3
for i in range(3):
    username=input("What is your username ")
    if username =="student":
    
        
        pwd=input("Whats your password ")
        if pwd=="password":
            print("welcome")
            studentname=input("What is your full name? ")
            studentage=input("What age ar you ")
        
    f = open('data.txt', 'wb')
    f.write("Student = " + str(studentname) + "\nAge = " + str(studentage))
    f.close()

  

And when i enter the username it will say:

f.write("Student = " + str(studentname) + "\nAge = " + str(studentage))
UnboundLocalError: local variable 'studentname' referenced before assignment
   

Does anyone know what I'm doing wrong.

SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
  • 1
    Please properly format your code to match your actual indentation. `studentname` won't be set though if `pwd=="password":` is false. – Carcigenicate Mar 08 '21 at 15:27

2 Answers2

1

studentname and studentage aren't defined unless password is correct. I made to modifications to your code to improve it:

  1. I put it in a while True statement so you need correct password to contiue
  2. I defined studentname and studentage 100% of time.
while True:
    pwd=input("Whats your password ")
    if pwd=="password":
        break
print("welcome")
studentname=input("What is your full name? ")
studentage=input("What age ar you ")
f = open('data.txt', 'wb')
f.write("Student = " + str(studentname) + "\nAge = " + str(studentage))
f.close()
CATboardBETA
  • 418
  • 6
  • 29
0

maybe because you're password is not correct, I think it is better to use an else statement as :

if pwd=="password":
    print("welcome")
    studentname=input("What is your full name? ")
    studentage=input("What age ar you ")
    
    f = open('data.txt', 'wb')
    f.write("Student = " + str(studentname) + "\nAge = " + str(studentage))
    f.close()
else:
    print('Password is wrong')
amer sam
  • 71
  • 3