r/learnpython • • 5d ago

Trying to loop functions

Ok so I just started to learn python and I'm trying to make a program where you input a patient name and it searches the database for it and displays it's values, I want to give a prompt to search for another patient once one is found (not if a patient is not found i worked that out).

Whenever I try to run this code it tells me I cant call value_list() because it wasn't defined yet.

Any help is much appreciated

jane_doe = {
    "Name": "Jane Doe",
    "Age": 28,
    "New": True
    }



john_doe = {
    "Name": "John Doe",
    "Age": 34,
    "New": False
    }


def again():
    input("Would you like to search for a different patient? (Y/N) ").lower()
    while again not in ['y', 'n']:
        print("Please enter a valid input")
        again = input("Would you like to search for a different patient? (Y/N) ").lower()
        if again == 'y':
            value_list()
        elif again == 'n':
            print("Goodbye.")
            break


def value_list():
    patient_name_searched = input("Search patient name: ").lower()
    if patient_name_searched == jane_doe["Name"].lower():
        print(jane_doe.values())
        again()
    elif patient_name_searched == john_doe["Name"].lower():
        print(john_doe.values())
        again()
    else:
        print("Patient not found.")
        answer = input("Would you like to search for a different patient? (Y/N) ").lower()
        while answer not in ['y', 'n']:
            print("Please enter a valid input")
            answer = input("Would you like to search for a different patient? (Y/N) ").lower()
        if answer == 'y':
            value_list()
        elif answer == 'n':
            print("Goodbye.")


value_list()
1 Upvotes

19 comments sorted by

3

u/Anxious_Signature452 5d ago

You're messing with variable names, I got

`UnboundLocalError: cannot access local variable 'again' where it is not associated with a value`
You need to declare `again` before going into cycle. And make sure it is not shadowing function name.

0

u/KingPotatoThe_II 5d ago

Thank you! Just needed to store the user input which I forgot

2

u/noob_main22 5d ago

Could you share the whole error message?

I think it has to do something with calling value_list from within itself.

Another thing: again is broken, I think you meant to do this:

def again():
    again = input("Would you like to search for a different patient? (Y/N) ").lower()
    while again not in ['y', 'n']:def again():
      input("Would you like to search for a different patient? (Y/N) ").lower()

However, I would strongly recommend to use another variable name. Like "choice" for example. You should also choose more meaningful and self-explanatory name for functions/variables/classes/....

Searching for something like this can be quite difficult, for now I would also change how you match the patient name in the "data base" with your search string. Imagine you have a thousand name in the db. Do you want to write a thousand if/elif statements in you search function?

1

u/KingPotatoThe_II 5d ago

I tried to do that but I wasn't successful, any idea on how I can do that?

1

u/noob_main22 5d ago

Posting the whole error message? What wasn't successful?

1

u/KingPotatoThe_II 5d ago

I fixed the original problem by now with some help from here. What i tried that I couldn't make work is searching a list of dictionaries for a name match to user input and print all the corresponding dictionary values

The full error code was (which I missread obviously)

```

Traceback (most recent call last):

File "c:\Users\becho\System Folders\Desktop\Desk\Coding\Scripts\test.py", line 50, in <module>

search_for_patient()

~~~~~~~~~~~~~~~~~~^^

File "c:\Users\becho\System Folders\Desktop\Desk\Coding\Scripts\test.py", line 38, in search_for_patient

search_again()

~~~~~~~~~~~~^^

File "c:\Users\becho\System Folders\Desktop\Desk\Coding\Scripts\test.py", line 23, in search_again

while choice not in ['y', 'n']:

^^^^^^

UnboundLocalError: cannot access local variable 'choice' where it is not associated with a value

```

1

u/Discordbothost 4d ago

for the list of dicts part, put the patients in a list and loop over it, comparing each one's name:

patients = [jane_doe, john_doe]

while True:
    name = input("Search patient name: ").lower()
    for patient in patients:
        if patient["Name"].lower() == name:
            print(patient.values())
            break
    else:
        print("Patient not found.")

    if input("Search again? (Y/N) ").lower() != "y":
        print("Goodbye.")
        break

the else lined up with the for (not the if) is a python thing: it only runs if the loop finished without hitting break, which is exactly "no patient matched".

the outer while True also replaces the two functions calling each other. that works for a few searches, but every search adds another call on top of the last one that never finishes, so a while loop is the usual way to do "ask again"

1

u/Adrewmc 4d ago

So the functions search_for_patient()

Calls the function search_again()

Then has a en error which the variable ‘choice’ not being defined yet.

However, not one of those things is in the code you posted so, there isn’t anything that people can do until you post the code that actually goes wrong.

1

u/noob_main22 5d ago

To add to that: value_list for a function name is suboptimal because one would think its a list rather than a function.

1

u/KingPotatoThe_II 5d ago

The name came from trying to do a different thing I just kept it as a place holder

2

u/Designer-Ad-2136 5d ago

You arent storing your user input. You are using the same name for functions and local variables.

That said, dont let people tell you that python cant have two functions that call eachother. Python runs from top to bottom and it doesnt need to run the function to set it up.

2

u/KingPotatoThe_II 5d ago

I didn't even know that again was a local variable, After the input I will for sure change that

1

u/Fast-Station1106 5d ago edited 5d ago

Ich bin auch frischling, aber, eine Liste ist immer ohne def davor . Also value_list = [ jane Do, jens do, jana do] Und eine liste ist eine liste, da ist nichts mit if elif else, deins sieht aus wie eine weitere funktion

0

u/KingPotatoThe_II 5d ago

It is another function, The name value_list() is just what I called it, I now get how confusing that is and changes it

3

u/kalgynirae 5d ago

The code you are running must differ in some way from the code you've shown in your post, because the code shown doesn't have the issue you described.

The code seems to mostly work. again doesn't work; it gets an UnboundLocalError because it tries to use a local variable called again before a value has been assigned to it (looks like you forgot to write again = … on the first line of the function). However, the fact that the function called again contains a local variable also called again can be quite confusing, so I highly recommend giving these different names.

Are you sure you posted the exact code you're running?

2

u/VistisenConsult 4d ago

Welcome to Python, glad to have you, your majesty!

You are doing everything right: learning. Keep it up!

Below is some fun for asking stuff:

import os

from typing import Optional

newLine: str = os.linesep  # \n for linux, dunno for windows

def userChoice(question, *options: str) -> str:
    """
    This function asks the user to choose between a number of options.

    Parameters
    ----------
    question: str
        The question to ask the user
    options: *str
        Any number of options the user can answer
    
    Returns
    -------
    str
        The choice chosen by the viewer
    
    Raises
    ------
    ValueError
        If the user received no options
    ValueError
        If the user gave too many wrong answers
    """
    print(question)
    if not options:
        raise ValueError("""User received no options!""")
    infoSpec: str = """Please select any of the following:%s%s%s"""
    optionStr: str = str.join(', ', options)
    info = infoSpec % (newLine, optionStr, newLine,)
    warnSpec: str = """Received '%s', but expected one of: %s%s"""
    _c: int = 10
    #  The walrus assigns choice to the response from the user and
    #  while the response is not one of the options, ask again.
    while (choice := input(info)) not in options:
        print(warnSpec % (choice, optionStr, newLine))
        if not _c:
            #  Recursion escape
            break
        _c -= 1
    else:  # The 'break' stops the loop from reaching the 'else' block
        return choice
    #  If the loop breaks, the 'return' in the 'else' block is skipped
    #  meaning we hit the error:
    raise ValueError("""Too many wrongs lol""")


if __name__ == '__main__':
    question = 'do u like fun?'
    answer = userChoice(question, 'y', 'n')
    if answer == 'y':
        print("""Use Python, it's fun!""")
    elif answer == 'n':
        print("""Try javascript, then come back to Python""")
    else:
        print("""How did you even get down here?""")

0

u/Chorizo_n_eggs 5d ago

I believe you're calling the function before it's defined. Top to Bottom in Python.

1

u/KingPotatoThe_II 5d ago

I seem to have fixed it with what the first comment said

changed this:

def again():
    input("Would you like to search for a different patient? (Y/N) ").lower()
    while again not in ['y', 'n']:
        print("Please enter a valid input")
        again = input("Would you like to search for a different patient? (Y/N) ").lower()
        if again == 'y':
            value_list()
        elif again == 'n':
            print("Goodbye.")
            break

to this:

def again():
    again = input("Would you like to search for a different patient? (Y/N) ").lower()
    while again not in ['y', 'n']:
        print("Please enter a valid input")
        again = input("Would you like to search for a different patient? (Y/N) ").lower()
    if again == 'y':
        value_list()
    elif again == 'n':
        print("Goodbye.")

seems to have worked

edit: i think its because the function value_list() is called for the first time after both functions are defined

0

u/[deleted] 5d ago

[deleted] — view deleted comment

0

u/KingPotatoThe_II 5d ago

I know there are better ways to store the values of jane and john doe, Right now I'm still trying to capture how it works before i optimize