1

I have the following code which prompts the user for a username, then checks if that username exists in a json file, if so the script should prompt the user 3 times maximum to enter another username, otherwise just accept the entered username and continue.

The issue comes when I try to reinitiate the for loop j = test1["users"][0] so that in the second attempt, this script checks the json file from the beginning not from the point it was.

When the script comes back to the for loop after the else statement, it just simply ignores the whole loop and continue to the next section of the code without any error...

The for loop is looping in a dictionary which is in a list:

#prompt for username
x["User Name"] = input("Please type your user name: ")
i = 0

#for loop to check if the entered username already exists
for j in test1["users"]:
    while j["User Name"] != x["User Name"] and i < 3:
        break
    else:
        print("username already exists, try again")
        x["User Name"] = input("Please type a new user name: ")
        i += 1
        j = test1["users"][0]

#prompts the user for additional information if username pass `succesfully`
x["First Name"] = input("Please type your first name: ")
x["Last Name"] = input("Please type your last name: ")
x["Age"] = input("Please type your age: ")

A sample of test1["users]:

{
    "users": [
        {
            "First Name": "jhon",
            "Age:": "30",
            "Last Name": "kerry",
            "User Name": "jhon",
            "Height": "170",
            "Weight": "70"
        },
javierquin
  • 11
  • 4
  • `j = test1["users"][0]` doesn't do anything, and you should use another kind of loop to do that, or a loop for the 3 trials around the for loop – B. Go Mar 27 '20 at 17:20
  • Welcome to stack overflow! In order to better understand your problem, please [edit] to include a sample of `test1["users"]` to make a [mcve]. Is there a reason you are looping in a dictionary instead of a lookup; `if x["User Name"] in j["User Name"].keys()` or similar? – G. Anderson Mar 27 '20 at 17:21
  • Thanks @G.Anderson, already added a sample of `test1["users"]`. The reason for looping in a dictionary is that I have a son file which I loaded through `json.load()`I will try your lookup suggestion, just was thinking that as that's a dictionary in a list I should loop instead of lookup. – javierquin Mar 27 '20 at 17:29
  • Thanks @B.Go, I have tried with different kinds of loops but all of them have presented issues. With a `while` and a `for` the `while` loop continues working either with a new username or an existing one, and that's what I don't want. That's why I'm trying a different approach. – javierquin Mar 27 '20 at 17:41

2 Answers2

0

For this case you dont want to use break but continue .

Here is a good tutorial where you can find more detailed explainations: https://docs.python.org/3/tutorial/controlflow.html?highlight=break

python00b
  • 113
  • 10
  • 1
    This `else` is not the same as in an if statement. see [here](https://book.pythontips.com/en/latest/for_-_else.html). The question also needed good indentation – AzyCrw4282 Mar 27 '20 at 17:21
  • 1
    [While: Else: is a valid construction in python](https://stackoverflow.com/questions/3295938/else-clause-on-python-while-statement) even if it's not great for understanding, and not widely used – G. Anderson Mar 27 '20 at 17:23
  • Thanks, never seen that before – python00b Mar 27 '20 at 17:24
  • Thanks @python00b, as the while is nested in the for loop, a `continue` statement will loop infinitely in the while statement. – javierquin Mar 27 '20 at 17:35
  • Ah i see, it would be more readable if you replaced the while else stuff with an ``` if not (condition) print("username exists") – python00b Mar 27 '20 at 17:38
  • Thanks again, in this case the while or if statement do the same. My concern is about how to start over the for loop so that it can check again all the existing usernames in a file. – javierquin Mar 27 '20 at 17:48
0

Guys thanks for your support, just wanted to say I solved the issue. Basically the challenge was:

  • I have a list of users in a json format or in a dictionary, in the end it doesn't matter.
  • I prompt the user to enter basic information and then I will append the information to the json file if the user name doesn't already exists there.
  • If the username already exists, the user has 3 additional attempts to enter another username.
  • The script must check again in the whole file if the new typed user exists or not in order to continue.

The issue was in the last point, because I needed to loop again in a for statement that could be in the middle of its job, which could result in duplicated records if the username existed in previous records.

My first attempt was to try to restart the for loop with this statement j = test1["users"][0] so that the loop started over, but that one didn't work. In the end the solution I came up with is using an additional loop that forces the for loop to be restarted. If you play with a while and a boolean variable the issue will get solved!! :)

That's the final code:

x["User Name"] = input("Please type your user name: ")
#initializing variables that restart for loop and restrict username input to 3
    i = True
    n = 0
#additional while loop to restart for loop
    while i and n <= 3:
        i = False
        if n == 3:
            print("Thank you")
            exit()
#looping a list in a diciontary
        for j in test1["users"]:
            while j["User Name"] != x["User Name"]:
                break
#telling the user the username already exists and prompting for new username
            else:
                print("existing user")
                x["User Name"] = input("Type new user name")
                n += 1
                i = True
                break
x["First Name"] = input("Please type your first name: ")
x["Last Name"] = input("Please type your last name: ")

Thanks everyone!!

javierquin
  • 11
  • 4